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] ]
Solution 1: DFS
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> one=new ArrayList<>();
List<List<Integer>> res=new ArrayList<>();
dfs(root,0,sum,one,res);
return res;
}
private void dfs(TreeNode x, int k, int sum, List<Integer> one, List<List<Integer>> res) {
if (x==null) return;
one.add(x.val);
k+=x.val;
if (x.left==null && x.right==null && k==sum) res.add(new ArrayList<Integer>(one));
dfs(x.left,k,sum,one,res);
dfs(x.right,k,sum,one,res);
one.remove(one.size()-1);
}
}
没有评论:
发表评论