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 email@example.com. 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
- Nodes from given two BSTs with sum equal to X
- Count of pairs violating BST property
- Construct all possible BSTs for keys 1 to N
- Check if two BSTs contain same set of elements
- Check if two given key sequences construct same BSTs
- Check for Identical BSTs without building the trees
- Merge two BSTs with limited extra space
- Merge two BSTs with constant extra space
- Generate two BSTs from the given array such that maximum height among them is minimum
- Number of pairs with a given sum in a Binary Search Tree
- 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
Improved By : shrikanth13