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 to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.
Although I am able to find all paths in tree that start at the root have the given sum, I am not able to do so for paths not not starting at the root.
If the tree is not empty, traverse through left subtree, calculate the sum of nodes and store it in sumLeft. Then, traverse through the right subtree, calculate the sum of nodes and store it in sumRight. Finally, calculate total sum = temp. data + sumLeft + sumRight.
Each leaf in a tree can be reached by exactly one path from the root node. If there are N leaves, there are N paths from the root to a leaf node. If there were more, there would be a leaf node with two paths to it.
Well, this is a tree, not a graph. So, you can do something like this:
Pseudocode:
global ResultList function ProcessNode(CurrentNode, CurrentSum) CurrentSum+=CurrentNode->Value if (CurrentSum==SumYouAreLookingFor) AddNodeTo ResultList for all Children of CurrentNode ProcessNode(Child,CurrentSum)
Well, this gives you the paths that start at the root. However, you can just make a tiny change:
for all Children of CurrentNode ProcessNode(Child,CurrentSum) ProcessNode(Child,0)
You might need to think about it for a second (I'm busy with other things), but this should basically run the same algorithm rooted at every node in the tree
EDIT: this actually gives the "end node" only. However, as this is a tree, you can just start at those end nodes and walk back up until you get the required sum.
EDIT 2: and, of course, if all values are positive then you can abort the descent if your current sum is >= the required one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With