[LeetCode] 113. Path Sum II 路径和 II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
112. Path Sum 的拓展,上一题只要求返回是否存在,这题要求输出具体的路径。
Java:
/** * 和原来的不一样,这题要完全遍历,使用track跟踪当前的进度,进入dfs时压进去,出dfs时推出,当时叶节点且和正好为0是,克隆添加到结果中。 * */ public class Solution { List<List<Integer>> list; LinkedList<Integer> track; public void dfs(TreeNode root,int sum){ if(root==null) return; sum-=root.val; track.add(root.val); if(sum==0 && root.left==null && root.right==null) list.add((LinkedList<Integer>)track.clone()); dfs(root.left,sum); dfs(root.right,sum); track.remove(track.size()-1); } public List<List<Integer>> pathSum(TreeNode root, int sum) { this.list=new ArrayList<List<Integer>>(); this.track=new LinkedList<Integer>(); dfs(root,sum); return this.list; } }
Python:
class Solution: # @param root, a tree node # @param sum, an integer # @return a list of lists of integers def pathSum(self, root, sum): return self.pathSumRecu([], [], root, sum) def pathSumRecu(self, result, cur, root, sum): if root is None: return result if root.left is None and root.right is None and root.val == sum: result.append(cur + [root.val]) return result cur.append(root.val) self.pathSumRecu(result, cur, root.left, sum - root.val) self.pathSumRecu(result, cur,root.right, sum - root.val) cur.pop() return result
C++:
class Solution { public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int>> res; vector<int> out; helper(root, sum, out, res); return res; } void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) { if (!node) return; out.push_back(node->val); if (sum == node->val && !node->left && !node->right) { res.push_back(out); } helper(node->left, sum - node->val, out, res); helper(node->right, sum - node->val, out, res); out.pop_back(); } };
类似题目:
[LeetCode] 437. Path Sum III 路径和 III
All LeetCode Questions List 题目汇总