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 (2, 3) and (4, 1) are pairs with sum equals 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 firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the maximum sum leaf to root path in a Binary Tree
- GCD from root to leaf path in an N-ary tree
- Check if there is a root to leaf path with given sequence
- Root to leaf path sum equal to a given number
- Root to leaf path with maximum distinct nodes
- Shortest root to leaf path sum equal to a given number
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path product equal to a given number
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Print the longest leaf to leaf path in a Binary tree
- Find the path from root to the given nodes of a tree for multiple queries
- Print root to leaf paths without using recursion
- Sum of all the numbers that are formed from root to leaf paths
- Print all root to leaf paths with there relative positions
- Remove nodes on root to leaf paths of length < K
- Given a binary tree, print all root-to-leaf paths
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Root to leaf paths having equal lengths in a Binary Tree