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] ]
DFS即可
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null) return ans;
helper(ans, new ArrayList(), root, 0, sum);
return ans;
}
private void helper(List<List<Integer>> ans, List<Integer> list, TreeNode root, int sum, int target){
sum += root.val;
if(root.left==null && root.right==null){
if(sum==target){
list.add(root.val);
ans.add(new ArrayList(list));
list.remove(list.size()-1);
}
return;
}
//if(sum>=target) return;
list.add(root.val);
if(root.left!=null) helper(ans, list, root.left, sum, target);
if(root.right!=null) helper(ans, list, root.right, sum, target);
list.remove(list.size()-1);
}
}