Triplet with a given sum in BST | Set 2
Given a binary search tree, and an integer X, the task is to find if there exists a triplet with sum X. Print Yes or No correspondingly. Note that the three nodes may not necessarily be distinct.
Examples:
Input: X = 15
5
/ \
3 7
/ \ / \
2 4 6 8
Output: Yes
{5, 5, 5} is one such triplet.
{3, 5, 7}, {2, 5, 8}, {4, 5, 6} are some others.
Input: X = 16
1
\
2
\
3
\
4
\
5
Output: No
Simple Approach: A simple approach will be to convert the BST to a sorted array and then find the triplet using three-pointers. This will take O(N) extra space where N is the number of nodes present in the Binary Search Tree. We have already discussed a similar problem in this article which takes O(N) extra space.
Better approach: We will solve this problem using a space-efficient method by reducing the additional space complexity to O(H) where H is the height of BST. For that, we will use the two pointer technique on BST.
We will traverse all the nodes for the tree one by one and for each node, we will try to find a pair with a sum equal to (X – curr->data) where ‘curr’ is the current node of the BST we are traversing.
We will use a technique similar to the technique discussed in this article for finding a pair.
Algorithm: Traverse each node of BST one by one and for each node:
- 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, thus we will increase the count by 1.
- 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 the left iterator doesn’t point to a node with larger value than right node.
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.size() and it2.size()) {
int v1 = it1.top()->data, v2 = it2.top()->data;
if (v1 + v2 == x)
return 1;
if (v1 > v2)
break ;
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 0;
}
bool existsTriplet(node* root, node* curr, int x)
{
if (curr == NULL)
return 0;
return (existsPair(root, x - curr->data)
|| existsTriplet(root, curr->left, x)
|| existsTriplet(root, curr->right, x));
}
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 = 24;
if (existsTriplet(root, root, x))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class GFG
{
static Node root;
static boolean existsPair(Node root, int x)
{
Stack<Node> it1 = new Stack<Node>();
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.size() > 0 && it2.size() > 0 )
{
int v1 = it1.peek().data;
int v2 = it2.peek().data;
if (v1 + v2 == x)
{
return true ;
}
if (v1 > v2)
{
break ;
}
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 ;
}
static boolean existsTriplet(Node root,
Node curr, int x )
{
if (curr == null )
{
return false ;
}
return (existsPair(root, x - curr.data) ||
existsTriplet(root, curr.left, x) ||
existsTriplet(root, curr.right, x));
}
public static void main (String[] args)
{
GFG tree = new GFG();
tree.root = new Node( 5 );
tree.root.left = new Node( 3 );
tree.root.right = new Node( 7 );
tree.root.left.left = new Node( 2 );
tree.root.left.right = new Node( 4 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 8 );
int x = 24 ;
if (existsTriplet(root, root, x))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self .left = None
self .right = None
def existsPair(root, x):
it1, it2 = [], []
c = root
while (c ! = None ):
it1.append(c)
c = c.left
c = root
while (c ! = None ):
it2.append(c)
c = c.right
while ( len (it1) > 0 and len (it2) > 0 ):
v1 = it1[ - 1 ].data
v2 = it2[ - 1 ].data
if (v1 + v2 = = x):
return 1
if (v1 > v2):
break
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 0
def existsTriplet(root, curr, x):
if (curr = = None ):
return 0
return (existsPair(root, x - curr.data)
or existsTriplet(root, curr.left, x)
or existsTriplet(root, curr.right, x))
if __name__ = = '__main__' :
root = Node( 5 )
root.left = Node( 3 )
root.right = Node( 7 )
root.left.left = Node( 2 )
root.left.right = Node( 4 )
root.right.left = Node( 6 )
root.right.right = Node( 8 )
x = 24
if (existsTriplet(root, root, x)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class GFG{
static Node root;
static bool existsPair(Node root, int x)
{
Stack<Node> it1 = new Stack<Node>();
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.Count > 0 && it2.Count > 0)
{
int v1 = it1.Peek().data;
int v2 = it2.Peek().data;
if (v1 + v2 == x)
{
return true ;
}
if (v1 > v2)
{
break ;
}
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 ;
}
static bool existsTriplet(Node root, Node curr, int x)
{
if (curr == null )
{
return false ;
}
return (existsPair(root, x - curr.data) ||
existsTriplet(root, curr.left, x) ||
existsTriplet(root, curr.right, x));
}
static public void Main()
{
GFG.root = new Node(5);
GFG.root.left = new Node(3);
GFG.root.right = new Node(7);
GFG.root.left.left = new Node(2);
GFG.root.left.right = new Node(4);
GFG.root.right.left = new Node(6);
GFG.root.right.right = new Node(8);
int x = 24;
if (existsTriplet(root, root, x))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "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.length > 0 && it2.length > 0)
{
let v1 = it1[it1.length - 1].data,
v2 = it2[it2.length - 1].data;
if (v1 + v2 == x)
return true ;
if (v1 > v2)
{
break ;
}
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 ;
}
function existsTriplet(root, curr, x)
{
if (curr == null )
{
return false ;
}
return (existsPair(root, x - curr.data) ||
existsTriplet(root, curr.left, x) ||
existsTriplet(root, curr.right, x));
}
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 = 24;
if (existsTriplet(root, root, x))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(N2)
Space complexity: O(H), since H extra space has been taken.
Last Updated :
25 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...