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]
]
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList> pathSum(TreeNode root, int sum) {
ArrayList path = new ArrayList();
ArrayList<ArrayList> result = new ArrayList<ArrayList>();
hasPathSum(root, sum, path, -1, result);
return result;
}
private void hasPathSum(TreeNode root, int sum, ArrayList a,
int index, ArrayList<ArrayList> result){
if(root == null) return;
a.add(root.val);
index++;
if (root.left == null && root.right == null){
if(root.val == sum) {
result.add(new ArrayList(a));
}
}
if(root.left!=null){
hasPathSum(root.left, sum - root.val, a, index, result);
}
if(root.right!=null){
hasPathSum(root.right, sum - root.val, a, index, result);
}
a.remove(index--);
}
}