Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x.
Input : BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 x = 16 Output : 3 The pairs are: (5, 11), (6, 10) and (8, 8)
Method 1: For each node value a in BST 1, search the value (x – a) in BST 2. If value found then increment the count. For searching a value in BST, refer this post.
Time complexity: O(n1 * h2), here n1 is number of nodes in first BST and h2 is height of second BST.
Method 2: Traverse BST 1 from smallest value to node to largest. This can be achieved with the help of iterative inorder traversal. Traverse BST 2 from largest value node to smallest. This can be achieved with the help of reverse inorder traversal. Perform these two traversals simultaneously. Sum up the corresponding node’s value from both the BSTs at a particular instance of traversals. If sum == x, then increment count. If x > sum, then move to the inorder successor of the current node of BST 1, else move to the inorder predecessor of the current node of BST 2. Perform these operations until either of the two traversals gets completed.
Pairs = 3
Time Complexity: O(n1 + n2)
Auxiliary Space: O(n1 + n2)
This article is contributed by Ayush Jauhari. 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.
- Find pairs with given sum such that pair elements lie in different BSTs
- Count of pairs violating BST property
- Check if two BSTs contain same set of elements
- Construct all possible BSTs for keys 1 to N
- Check if two given key sequences construct same BSTs
- Merge two BSTs with limited extra space
- 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
- Largest number in BST which is less than or equal to N
- Smallest number in BST which is greater than or equal to N
- Check whether the sum of element of a node is equal to the given key value
- Root to leaf path sum equal to a given number in BST
- Largest number less than or equal to N in BST (Iterative Approach)
- Count BST nodes that lie in a given range
Improved By : shrikanth13