Question:
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] ]
Code:
public static void sumAll(Node root, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> listAll) {
if (root == null) return;
list.add(root.v);
if (root.leftChild == null && root.rightChild == null) {
listAll.add(new ArrayList<Integer>(list));
}
sumAll(root.leftChild, list, listAll);
sumAll(root.rightChild, list, listAll);
list.remove(list.size() - 1);
}
class Node {
Node leftChild = null;
Node rightChild = null;
int v;
Node(int value) {
this.v = value;
}
}