[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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** * 和原来的不一样,这题要完全遍历,使用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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步