/**
1357 · Path Sum II
Algorithms
Medium
Accepted Rate
78%
DescriptionSolutionNotesDiscussLeaderboard
Description
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
A leaf is a node with no children.
Example
Example 1:
Input: root = {5,4,8,11,#,13,4,7,2,#,#,5,1}, sum = 22
5
/
4 8
/ /
11 13 4
/ \ /
7 2 5 1
Output: [[5,4,11,2],[5,8,4,5]]
Explanation:
The sum of the two paths is 22:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
Example 2:
Input: root = {10,6,7,5,2,1,8,#,9}, sum = 18
10
/
6 7
/ \ /
5 2 1 8
\
9
Output: [[10,6,2],[10,7,1]]
Explanation:
The sum of the two paths is 18:
10 + 6 + 2 = 18
10 + 7 + 1 = 18
https://blog.csdn.net/u011809767/article/details/77102405?utm_source=blogkpcl8
https://www.jianshu.com/p/8dbe00d52865
https://www.lintcode.com/problem/1357/
*/
参考有个老哥的解法写了一个go语言的,但是没过,有时间改一下。
//WA
func pathSum(root *TreeNode, sum int) [][]int {
// Write your code here.
var res [][]int
var re []int
dfs(root, &res, &re, sum)
return res
}
func dfs(root *TreeNode, res *[][]int, re *[]int, sum int) {
if root == nil {
return;
}
if root.Val == sum && root.Left == nil && root.Right == nil {
*re = append(*re, root.Val)
*res = append(*res, *re)
*re = (*re)[:len(*re) - 1]
return;
}
re1 := append(*re, root.Val)
dfs(root.Left, res, &re1, sum - root.Val)
re2 := append(*re, root.Val)
dfs(root.Right, res, &re2, sum - root.Val)
}
下面转载下另一个老哥的正确的版本,是AC的
public List<List<Integer>> pathSum2(TreeNode root, int sum) {
List<Integer> out = new ArrayList<Integer>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
pathSum2Helper(root, sum, out, res);
return res;
}
public void pathSum2Helper(TreeNode root, int sum, List<Integer> out, List<List<Integer>> res) {
if (root == null) {
return;
}
int val = root.val;
if (val == sum && root.left == null && root.right == null) {
out.add(val);
res.add(new ArrayList<Integer>(out));
out.remove(out.size() - 1);
return;
}
out.add(val);
pathSum2Helper(root.left, sum - val, out, res);
pathSum2Helper(root.right, sum - val, out, res);
out.remove(out.size() - 1);
}