05 August 2008
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and ‘sum = 22’,
1
2
3
4
5
6
7
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
1
2
3
4
[
[5,4,11,2],
[5,8,4,5]
]
解法跟上面类似,只是需要找出所有的路径。
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
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> onePath = new ArrayList<>();
dfs(root, sum, result, onePath);
return result;
}
// backtracking的写法
private void dfs(TreeNode root, int sum, List<List<Integer>> result, List<Integer> onePath) {
if (root == null) {
return;//说明这条path已经走完,不符合要求,需要return
}
onePath.add(new Integer(root.val));//?
if (root.left == null && root.right == null && sum == root.val) {
result.add(new ArrayList<>(onePath));
onePath.remove(onePath.size() - 1);
return;//说明这条path已经走完,已经加入result,需要return
}
dfs(root.left, sum - root.val, result, onePath);
dfs(root.right, sum - root.val, result, onePath);
// backtracking中的回退不能忘记,退到当前节点的上一个节点
onePath.remove(onePath.size() - 1);
}
}