Given a binary search tree and a target value, find all the paths (if there exists more than one) which sum up to the target value. It can be any path in the tree. It doesn\'t h
Old question, but here's my stab at it - should be O(n) time as your visiting each node only once:
public static List> pathSum(Node head, int sum) {
List currentPath = new ArrayList();
List> validPaths = new ArrayList>();
dfsSum(head, sum, currentPath, validPaths);
return validPaths;
}
public static void dfsSum(Node head, int sum, List currentPath, List> validPaths) {
if (head == null) return;
currentPath.add(head.val);
if (head.left == null && head.right == null && sum == head.val) {
validPaths.add(new ArrayList(currentPath));
}
dfsSum(head.left, sum - head.val, new ArrayList(currentPath), validPaths);
dfsSum(head.right, sum - head.val, new ArrayList(currentPath), validPaths);
}
And the node class:
class Node {
public int val;
public Node left;
public Node right;
public Node(int val) {
this.val = val;
}
}