Pair with a given sum in BST | Set 2
Last Updated :
18 Aug, 2021
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.
Examples:
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:
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* left;
node* right;
node( int data)
{
this ->data = data;
left = NULL;
right = NULL;
}
};
bool existsPair(node* root, int x)
{
stack<node *> it1, it2;
node* c = root;
while (c != NULL)
it1.push(c), c = c->left;
c = root;
while (c != NULL)
it2.push(c), c = c->right;
while (it1.top() != it2.top()) {
int v1 = it1.top()->data, v2 = it2.top()->data;
if (v1 + v2 == x)
return true ;
if (v1 + v2 < x) {
c = it1.top()->right;
it1.pop();
while (c != NULL)
it1.push(c), c = c->left;
}
else {
c = it2.top()->left;
it2.pop();
while (c != NULL)
it2.push(c), c = c->right;
}
}
return false ;
}
int main()
{
node* root = new node(5);
root->left = new node(3);
root->right = new node(7);
root->left->left = new node(2);
root->left->right = new node(4);
root->right->left = new node(6);
root->right->right = new node(8);
int x = 5;
if (existsPair(root, x))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class node
{
int data;
node left;
node right;
node( int data)
{
this .data = data;
left = null ;
right = null ;
}
};
static boolean existsPair(node root, int x)
{
Stack<node > it1 = new Stack<node>(), it2 = new Stack<node>();
node c = root;
while (c != null )
{
it1.push(c);
c = c.left;
}
c = root;
while (c != null )
{
it2.push(c);
c = c.right;
}
while (it1.peek() != it2.peek())
{
int v1 = it1.peek().data, v2 = it2.peek().data;
if (v1 + v2 == x)
return true ;
if (v1 + v2 < x)
{
c = it1.peek().right;
it1.pop();
while (c != null )
{
it1.push(c);
c = c.left;
}
}
else
{
c = it2.peek().left;
it2.pop();
while (c != null )
{
it2.push(c);
c = c.right;
}
}
}
return false ;
}
public static void main(String[] args)
{
node root = new node( 5 );
root.left = new node( 3 );
root.right = new node( 7 );
root.left.left = new node( 2 );
root.left.right = new node( 4 );
root.right.left = new node( 6 );
root.right.right = new node( 8 );
int x = 5 ;
if (existsPair(root, x))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
class node:
def __init__ ( self , key):
self .data = key
self .left = None
self .right = None
def existsPair(root1, x):
it1, it2 = [], []
c = root1
while (c ! = None ):
it1.append(c)
c = c.left
c = root1
while (c ! = None ):
it2.append(c)
c = c.right
while (it1[ - 1 ] ! = it2[ - 1 ]):
v1 = it1[ - 1 ].data
v2 = it2[ - 1 ].data
if (v1 + v2 = = x):
return True
if (v1 + v2 < x):
c = it1[ - 1 ].right
del it1[ - 1 ]
while (c ! = None ):
it1.append(c)
c = c.left
else :
c = it2[ - 1 ].left
del it2[ - 1 ]
while (c ! = None ):
it2.append(c)
c = c.right
return False
if __name__ = = '__main__' :
root2 = node( 5 )
root2.left = node( 3 )
root2.right = node( 7 )
root2.left.left = node( 2 )
root2.left.right = node( 4 )
root2.right.left = node( 6 )
root2.right.right = node( 8 )
x = 5
if (existsPair(root2, x)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class node
{
public int data;
public node left;
public node right;
public node( int data)
{
this .data = data;
left = null ;
right = null ;
}
};
static bool existsPair(node root, int x)
{
Stack<node > it1 = new Stack<node>(),
it2 = new Stack<node>();
node c = root;
while (c != null )
{
it1.Push(c);
c = c.left;
}
c = root;
while (c != null )
{
it2.Push(c);
c = c.right;
}
while (it1.Peek() != it2.Peek())
{
int v1 = it1.Peek().data,
v2 = it2.Peek().data;
if (v1 + v2 == x)
return true ;
if (v1 + v2 < x)
{
c = it1.Peek().right;
it1.Pop();
while (c != null )
{
it1.Push(c);
c = c.left;
}
}
else
{
c = it2.Peek().left;
it2.Pop();
while (c != null )
{
it2.Push(c);
c = c.right;
}
}
}
return false ;
}
public static void Main(String[] args)
{
node root = new node(5);
root.left = new node(3);
root.right = new node(7);
root.left.left = new node(2);
root.left.right = new node(4);
root.right.left = new node(6);
root.right.right = new node(8);
int x = 5;
if (existsPair(root, x))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
class node
{
constructor(data)
{
this .data = data;
this .left = this .right = null ;
}
}
function existsPair(root, x)
{
let it1 = [], it2 = [];
let c = root;
while (c != null )
{
it1.push(c);
c = c.left;
}
c = root;
while (c != null )
{
it2.push(c);
c = c.right;
}
while (it1[it1.length-1] != it2[it2.length-1])
{
let v1 = it1[it1.length - 1].data,
v2 = it2[it2.length - 1].data;
if (v1 + v2 == x)
return true ;
if (v1 + v2 < x)
{
c = it1[it1.length - 1].right;
it1.pop();
while (c != null )
{
it1.push(c);
c = c.left;
}
}
else
{
c = it2[it2.length - 1].left;
it2.pop();
while (c != null )
{
it2.push(c);
c = c.right;
}
}
}
return false ;
}
let root = new node(5);
root.left = new node(3);
root.right = new node(7);
root.left.left = new node(2);
root.left.right = new node(4);
root.right.left = new node(6);
root.right.right = new node(8);
let x = 5;
if (existsPair(root, x))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(N).
Share your thoughts in the comments
Please Login to comment...