Given two Binary search trees and an integer X, the task is to find a pair of nodes, one belonging to the first BST and the second belonging to other such that their sum is equal to X. If there exists such a pair, print Yes else print No.
Input: X = 100 BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 11 \ 13 Output: No There is no such pair with given value. Input: X = 16 BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 11 \ 13 Output: Yes 5 + 11 = 16
Approach: We will solve this problem using two pointer approach.
We will create a forward iterator on the first BST and backward on the second. Thus, we will maintain forward and a backward iterator that will iterate the BSTs in the order of in-order and reverse in-order traversal respectively.
- Create a forward and backward iterator for first and second BST respectively. Let’s say the value of nodes they are pointing at are v1 and v2.
- Now at each step,
- If v1 + v2 = X, we found a pair.
- If v1 + v2 less than or equal to x, we will make forward iterator point to the next element.
- If v1 + v2 greater than x, we will make backward iterator point to the previous element.
- We will continue the above while both iterators are pointing to a valid node.
Below is the implementation of the above approach:
- Count pairs from two BSTs whose sum is equal to a given value x
- 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
- Find pairs with given sum such that pair elements lie in different 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
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Sum of all odd nodes in the path connecting two given nodes
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Print levels with odd number of nodes and even number of nodes
- Count BST nodes that lie in a given range
- Two nodes of a BST are swapped, correct the BST | Set-2
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.