Given two Binary Search Tree (BSTs) and a value X, the problem is to print all pairs from both the BSTs whose sum is greater than the given value X.
Input: BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 X = 20 Output: The pairs are: (3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)
Naive Approach: For each node value A in BST 1, search the value in BST 2 which is greater than the (X – A). If the value is found then print the pair.
Time complexity: O(n1 * h2), where n1 is the number of nodes in first BST and h2 is the height of the second BST.
- Traverse BST 1 from smallest value to node to largest by taking index i. This can be achieved with the help of inorder traversal.
- Traverse BST 2 from largest value node to smallest by taking index j. This can be achieved with the help of inorder traversal.
- Perform these two traversals one by one and store into two array.
Sum up the corresponding node’s value from both the BSTs at a particular instance of traversals.
- If sum > x, then print pair and decrement j by 1.
- If x > sum, then increment i by 1.
Perform these operations until either of the two traversals gets completed.
Below is the implementation of the above approach:
(3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)
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.
- Count pairs from two BSTs whose sum is equal to a given value x
- Find pairs with given sum such that pair elements lie in different BSTs
- Count pairs in BST with sum greater than K
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Check if two BSTs contain same set of elements
- Construct all possible BSTs for keys 1 to N
- Nodes from given two BSTs with sum equal to X
- Split a BST into two balanced BSTs based on a value K
- Check if two given key sequences construct same BSTs
- Merge two BSTs with limited extra space
- Total number of BSTs using array elements
- Check for Identical BSTs without building the trees
- Merge two BSTs with constant extra space
- Generate two BSTs from the given array such that maximum height among them is minimum
- Add all greater values to every node in a given BST
- Transform a BST to greater sum tree
- Count of nodes that are greater than Ancestors
- Count greater nodes in AVL tree
- Number of nodes greater than a given value in n-ary tree
- Smallest Greater Element on Right Side
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.