[leetcode]Path Sum II
2013-06-18 20:46
351 查看
Path Sum 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
return
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] ] 这个问题需要返回每条满足sum值的所有路径。思路是:后序遍历,回溯时将当前node.val添加到左右子树的结果中。 递归: List<List<Int>> path_sum_helper(Treenode node, int current_sum, int depth, int sum_aim): if (node is leaf-node): r = [[]] if (current_sum == sum_aim): r_i = [] r_i[depth] = node.val r.add(r_i) return r else: r = [[]] if(node.left != null): left_ = path_sum_helper(node.left, current_sum + node.left.val, depth + 1, sum_aim) if (left_ != null): r = left_; for(r_ : r): r_[level] = node.val // similar for right sub-tree // need to merge left and right results return r
相关文章推荐
- leetcode 113 Path Sum II
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- [leetcode刷题系列]Path Sum II
- 【LeetCode】Path Sum II
- [LeetCode] Path Sum II 解题报告
- Leetcode 113. Path Sum II
- Leetcode-113. Path Sum II
- leetcode之Path Sum II
- Path Sum & Path Sum II | LeetCode DFS
- [Leetcode] 113. Path Sum II 解题报告
- leetcode 113. Path Sum II
- Path Sum II - LeetCode 113
- leetcode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode 39 Path Sum II
- leetcode Unique Paths & Unique Paths II & Minimum Path Sum
- LeetCode 113 Path Sum II
- Leetcode: Unique Path I & II, Minimum Path Sum, Triangle
- [LeetCode] Path Sum II
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】