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 andsum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) {
return ans;
}
helper(root, new ArrayList<Integer>(), ans, 0, sum);
return ans;
}
private void helper(TreeNode root, List<Integer> path, List<List<Integer>> ans, int sum, int target) {
path.add(root.val);
sum += root.val;
if (root.left == null && root.right == null) {
if (sum == target) {
ans.add(new ArrayList<Integer>(path));
}
// path.remove(path.size() - 1);
// return; 这两句可加可不加
}
if (root.left != null) {
helper(root.left, path, ans, sum, target);
}
if (root.right != null) {
helper(root.right, path, ans, sum, target);
}
path.remove(path.size() - 1);
}
或者这样写:
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null){
return res;
}
List<Integer> path = new ArrayList<Integer>();
path.add(root.val);
helper(root, root.val, target, path, res);
return res;
}
private void helper(TreeNode root, int sum, int target, List<Integer> path, List<List<Integer>> res){
if(root.left == null && root.right == null){
if(sum == target){
res.add(new ArrayList<Integer>(path));
}
return;
}
if(root.left != null){
path.add(root.left.val);
helper(root.left, sum + root.left.val, target, path, res);
path.remove(path.size() - 1);
}
if(root.right != null){
path.add(root.right.val);
helper(root.right, sum + root.right.val, target, path, res);
path.remove(path.size() - 1);
}
}