Problem(root to leaf)
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
A valid path is from root node to any of the leaf nodes.
Example
Given a binary tree, and target = 5:
1
/ \
2 4
/ \
2 3
return
[
[1, 2, 2],
[1, 4]
]
思路(Traverse)
- backtrack
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
List<List<Integer>> result = new ArrayList<>();
helper(root, target, result, 0, new ArrayList<Integer>());
return result;
}
private void helper(TreeNode root, int target, List<List<Integer>> result, int sum, List<Integer> path) {
if (root == null) {
return;
}
sum += root.val;
path.add(root.val);
if (root.left == null && root.right == null) {
if (target == sum) {
result.add(new ArrayList<Integer>(path));
}
}
helper(root.left, target, result, sum, path);
helper(root.right, target, result, sum, path);
sum -= root.val;
path.remove(path.size() - 1);
}