Print all pairs from two BSTs whose sum is greater than the given value
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.
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)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.