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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if there is a root to leaf path with given sequence
- Find the maximum sum leaf to root path in a Binary Tree
- Find all root to leaf path sum of a Binary Tree
- Print all root to leaf paths with there relative positions
- Root to leaf path sum equal to a given number
- Sum of nodes on the longest path from root to leaf node
- Shortest root to leaf path sum equal to a given number
- Print the longest leaf to leaf path in a Binary tree
- Root to leaf path with maximum distinct nodes
- Root to leaf path product equal to a given number
- Print the first shortest root to leaf path in a Binary Tree
- GCD from root to leaf path in an N-ary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Sum of all the numbers that are formed from root to leaf paths
- Find maximum GCD value from root to leaf in a Binary tree
- Check if a Binary Tree consists of a pair of leaf nodes with sum K
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths