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] ]
找出所有满足从根节点到叶子节点和为给定sum的路径
还是DFS
public class Solution {
public void findPathSum(TreeNode root, int sum,ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> list) {
if (sum == root.val && root.left == null && root.right == null) {
list.add(root.val);
ret.add(new ArrayList<Integer>(list));
list.remove(list.size() - 1);
return;
}
list.add(root.val);
if (root.left != null)
findPathSum(root.left, sum - root.val, ret, list);
if (root.right != null)
findPathSum(root.right, sum - root.val, ret, list);
list.remove(list.size() - 1);
}
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (root == null)
return ret;
ArrayList<Integer> list = new ArrayList<Integer>();
findPathSum(root, sum, ret, list);
return ret;
}
}