Find if there is a pair in root to a leaf path with sum equals to root’s data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root’s data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root’s data.
The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem.
- Create an empty hash table.
- Start traversing tree in Preorder fashion.
- If we reach a leaf node, we return false.
- For every visited node, check if root’s data minus current node’s data exists in hash table or not. If yes, return true. Else insert current node in hash table.
- Recursively check in left and right subtrees.
- Remove current node from hash table so that it doesn’t appear in other root to leaf paths.
Below is the implementation of above idea.
Time Complexity: O(n) under the assumption that hash search, insert and erase take O(1) time.
Exercise : Extend the above solution to print all root to leaf paths that have a pair with sum equals to root’s data.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.