Groupon面经:Find paths in a binary tree summing to a target value - neverlandly - 博客园
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.
Traverse through the tree from the root and do a post-order gathering of all path sums. Use a hashtable at each node to store the possible paths rooted at a node and going down-only. Key is the path sum, value is the actual path. We can construct all paths going through a node from itself and its childrens' paths.
Here is psuedo-code that implements the above, but stores only the sums and not the actual paths. For the paths themselves, you need to store the end node in the hashtable (we know where it starts, and there's only one path between two nodes in a tree).
Read full article from Groupon面经:Find paths in a binary tree summing to a target value - neverlandly - 博客园
No comments:
Post a Comment