The following is an interview question.
You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t
We can solve it with tree-structure dynamic programming, and both the time and space complexity is O(n^2), where n is the number of all the tree nodes.
The idea is as follows:
For a tree node, we keep a set recording all possible sums starting from u to its all descendants. Then recursively, any node's set can be updated by its two children, specifically, by merging two children's sets.
The pseudocode is:
bool findPath(Node u, Set uset, int finalSum) {
Set lset, rset;
if (findPath(u.left, lset, finalSum) || findPath(u.right, rset, finalSum)) return true;
for (int s1 : lset) {
if (finalSum - u.val - s1 == 0 || rset.contains(finalSum - u.val - s1)) return true;
// first condition means a path from u to some descendant in u's left child
// second condition means a path from some node in u's left child to some node in u's right child
uset.insert(s1 + u.val); // update u's set
}
for (int s2 : rset) {
if (finalSum - u.val - s2 == 0) return true;
// don't forget the path from u to some descendant in u's right child
uset.insert(s2 + u.val); // update u's set
}
return false;
}
I notice the original question is to find all paths, but the algorithm above is to find whether existed. I think the idea is similar, but this version makes the problem easier to explain :)