Given a binary search tree, and an integer X, the task is to check if there exists a pair of distinct nodes in BST with sum equal to X. If yes then print Yes else print No.
Input: X = 5 5 / \ 3 7 / \ / \ 2 4 6 8 Output: Yes 2 + 3 = 5. Thus, the answer is "Yes" Input: X = 10 1 \ 2 \ 3 \ 4 \ 5 Output: No
Approach: We have already discussed a hash based approach in this article. The space complexity of this is O(N) where N is the number of nodes in BST.
In this article, we will solve the same problem using a space efficient method by reducing the space complexity to O(H) where H is the height of BST. For that, we will use two pointer technique on BST. Thus, we will maintain a forward and a backward iterator that will iterate the BST in the order of in-order and reverse in-order traversal respectively. Following are the steps to solve the problem:
- Create a forward and backward iterator for BST. 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 < x, we will make forward iterator point to the next element.
- If v1 + v2 > x, we will make backward iterator point to the previous element.
- If we find no such pair, answer will be “No”.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find a pair with given sum in BST
- Stack of Pair in C++ STL with Examples
- Find a pair with given sum in a Balanced BST
- Pair with minimum absolute difference | BST
- Construct an array from its pair-product
- Longest path between any pair of vertices
- Find pairs with given sum such that pair elements lie in different BSTs
- Number of pair of positions in matrix which are not accessible
- Maximum pair sum in the given index ranges of an Array
- Find count of pair of nodes at even distance
- Longest subsequence such that absolute difference between every pair is atmost 1
- Pair with minimum absolute difference after solving each query
- Find the number of pair of Ideal nodes in a given tree
- Find the shortest distance between any pair of two different good nodes
- Minimum cost to reverse edges such that there is path between every pair of nodes
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.