Find if there is a triplet in a Balanced BST that adds to zero
Given a Balanced Binary Search Tree (BST), the task is to write a function isTripletPresent() which returns true if there is a triplet in the given BST with a sum equal to 0, otherwise returns false.
The expected time complexity should be O(n^2) and only O(Logn) extra space can be used. You can modify the given Binary Search Tree. Note that the height of a Balanced BST is always O(Log n).
For example, isTripletPresent() should return true for following BST because there is a triplet with sum 0, the triplet is {-13, 6, 7}.
The Brute Force Solution is to consider each triplet in BST and check whether the sum adds up to zero. The time complexity of this solution will be O(n^3).
A Better Solution is to create an auxiliary array and store the Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Once we have the Inorder traversal, we can use method 2 of this post to find the triplet with a sum equals to 0. This solution works in O(n^2) time but requires O(n) auxiliary space.
Following is the solution that works in O(n^2) time and uses O(Logn) extra space:
- Convert given BST to Doubly Linked List (DLL)
- Now iterate through every node of DLL and if the key of node is negative, then find a pair in DLL with sum equal to key of current node multiplied by -1. To find the pair, we can use the approach used in hasArrayTwoCandidates() in method 1 of this post.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class node
{
public :
int key;
node *left;
node *right;
};
void convertBSTtoDLL(node* root, node** head, node** tail)
{
if (root == NULL)
return ;
if (root->left)
convertBSTtoDLL(root->left, head, tail);
root->left = *tail;
if (*tail)
(*tail)->right = root;
else
*head = root;
*tail = root;
if (root->right)
convertBSTtoDLL(root->right, head, tail);
}
bool isPresentInDLL(node* head, node* tail, int sum)
{
while (head != tail)
{
int curr = head->key + tail->key;
if (curr == sum)
return true ;
else if (curr > sum)
tail = tail->left;
else
head = head->right;
}
return false ;
}
bool isTripletPresent(node *root)
{
if (root == NULL)
return false ;
node* head = NULL;
node* tail = NULL;
convertBSTtoDLL(root, &head, &tail);
while ((head->right != tail) && (head->key < 0))
{
if (isPresentInDLL(head->right, tail, -1*head->key))
return true ;
else
head = head->right;
}
return false ;
}
node* newNode( int num)
{
node* temp = new node();
temp->key = num;
temp->left = temp->right = NULL;
return temp;
}
node* insert(node* root, int key)
{
if (root == NULL)
return newNode(key);
if (root->key > key)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
int main()
{
node* root = NULL;
root = insert(root, 6);
root = insert(root, -13);
root = insert(root, 14);
root = insert(root, -8);
root = insert(root, 15);
root = insert(root, 13);
root = insert(root, 7);
if (isTripletPresent(root))
cout << "Present" ;
else
cout << "Not Present" ;
return 0;
}
|
C
#include<stdio.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
void convertBSTtoDLL(node* root, node** head, node** tail)
{
if (root == NULL)
return ;
if (root->left)
convertBSTtoDLL(root->left, head, tail);
root->left = *tail;
if (*tail)
(*tail)->right = root;
else
*head = root;
*tail = root;
if (root->right)
convertBSTtoDLL(root->right, head, tail);
}
bool isPresentInDLL(node* head, node* tail, int sum)
{
while (head != tail)
{
int curr = head->key + tail->key;
if (curr == sum)
return true ;
else if (curr > sum)
tail = tail->left;
else
head = head->right;
}
return false ;
}
bool isTripletPresent(node *root)
{
if (root == NULL)
return false ;
node* head = NULL;
node* tail = NULL;
convertBSTtoDLL(root, &head, &tail);
while ((head->right != tail) && (head->key < 0))
{
if (isPresentInDLL(head->right, tail, -1*head->key))
return true ;
else
head = head->right;
}
return false ;
}
node* newNode( int num)
{
node* temp = new node;
temp->key = num;
temp->left = temp->right = NULL;
return temp;
}
node* insert(node* root, int key)
{
if (root == NULL)
return newNode(key);
if (root->key > key)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
int main()
{
node* root = NULL;
root = insert(root, 6);
root = insert(root, -13);
root = insert(root, 14);
root = insert(root, -8);
root = insert(root, 15);
root = insert(root, 13);
root = insert(root, 7);
if (isTripletPresent(root))
printf ( "Present" );
else
printf ( "Not Present" );
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class node
{
int key;
node left;
node right;
};
static node head;
static node tail;
static void convertBSTtoDLL(node root)
{
if (root == null )
return ;
if (root.left != null )
convertBSTtoDLL(root.left);
root.left = tail;
if (tail != null )
(tail).right = root;
else
head = root;
tail = root;
if (root.right != null )
convertBSTtoDLL(root.right);
}
static boolean isPresentInDLL(node head, node tail, int sum)
{
while (head != tail)
{
int curr = head.key + tail.key;
if (curr == sum)
return true ;
else if (curr > sum)
tail = tail.left;
else
head = head.right;
}
return false ;
}
static boolean isTripletPresent(node root)
{
if (root == null )
return false ;
head = null ;
tail = null ;
convertBSTtoDLL(root);
while ((head.right != tail) && (head.key < 0 ))
{
if (isPresentInDLL(head.right, tail, - 1 *head.key))
return true ;
else
head = head.right;
}
return false ;
}
static node newNode( int num)
{
node temp = new node();
temp.key = num;
temp.left = temp.right = null ;
return temp;
}
static node insert(node root, int key)
{
if (root == null )
return newNode(key);
if (root.key > key)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return root;
}
public static void main(String[] args)
{
node root = null ;
root = insert(root, 6 );
root = insert(root, - 13 );
root = insert(root, 14 );
root = insert(root, - 8 );
root = insert(root, 15 );
root = insert(root, 13 );
root = insert(root, 7 );
if (isTripletPresent(root))
System.out.print( "Present" );
else
System.out.print( "Not Present" );
}
}
|
Python3
class Node:
def __init__( self ):
self .key = 0 ;
self .left = None ;
self .right = None ;
head = Node();
tail = Node();
def convertBSTtoDLL(root):
if (root = = None ):
return ;
global tail;
global head;
if (root.left ! = None ):
convertBSTtoDLL(root.left);
root.left = tail;
if (tail ! = None ):
(tail).right = root;
else :
head = root;
tail = root;
if (root.right ! = None ):
convertBSTtoDLL(root.right);
def isPresentInDLL(head, tail, s):
while (head ! = tail):
curr = head.key + tail.key;
if (curr = = s):
return True ;
elif (curr > s):
tail = tail.left;
else :
head = head.right;
return False ;
def isTripletPresent(root):
if (root = = None ):
return False ;
global tail;
global head;
head = None ;
tail = None ;
convertBSTtoDLL(root);
while ((head.right ! = tail) and (head.key < 0 )):
if (isPresentInDLL(head.right, tail, - 1 * head.key)):
return True ;
else :
head = head.right;
return False ;
def newNode(num):
temp = Node();
temp.key = num;
temp.left = temp.right = None ;
return temp;
def insert(root, key):
if (root = = None ):
return newNode(key);
if (root.key > key):
root.left = insert(root.left, key);
else :
root.right = insert(root.right, key);
return root;
if __name__ = = '__main__' :
root = None ;
root = insert(root, 6 );
root = insert(root, - 13 );
root = insert(root, 14 );
root = insert(root, - 8 );
root = insert(root, 15 );
root = insert(root, 13 );
root = insert(root, 7 );
if (isTripletPresent(root)):
print ( "Present" );
else :
print ( "Not Present" );
|
C#
using System;
public class GFG
{
public class node
{
public int key;
public node left;
public node right;
};
static node head;
static node tail;
static void convertBSTtoDLL(node root)
{
if (root == null )
return ;
if (root.left != null )
convertBSTtoDLL(root.left);
root.left = tail;
if (tail != null )
(tail).right = root;
else
head = root;
tail = root;
if (root.right != null )
convertBSTtoDLL(root.right);
}
static bool isPresentInDLL(node head, node tail, int sum)
{
while (head != tail)
{
int curr = head.key + tail.key;
if (curr == sum)
return true ;
else if (curr > sum)
tail = tail.left;
else
head = head.right;
}
return false ;
}
static bool isTripletPresent(node root)
{
if (root == null )
return false ;
head = null ;
tail = null ;
convertBSTtoDLL(root);
while ((head.right != tail) && (head.key < 0))
{
if (isPresentInDLL(head.right, tail, -1*head.key))
return true ;
else
head = head.right;
}
return false ;
}
static node newNode( int num)
{
node temp = new node();
temp.key = num;
temp.left = temp.right = null ;
return temp;
}
static node insert(node root, int key)
{
if (root == null )
return newNode(key);
if (root.key > key)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return root;
}
public static void Main(String[] args)
{
node root = null ;
root = insert(root, 6);
root = insert(root, -13);
root = insert(root, 14);
root = insert(root, -8);
root = insert(root, 15);
root = insert(root, 13);
root = insert(root, 7);
if (isTripletPresent(root))
Console.Write( "Present" );
else
Console.Write( "Not Present" );
}
}
|
Javascript
<script>
class node {
constructor(val) {
this .key = val;
this .left = null ;
this .right = null ;
}
}
var head;
var tail;
function convertBSTtoDLL( root) {
if (root == null )
return ;
if (root.left != null )
convertBSTtoDLL(root.left);
root.left = tail;
if (tail != null )
(tail).right = root;
else
head = root;
tail = root;
if (root.right != null )
convertBSTtoDLL(root.right);
}
function isPresentInDLL( head, tail , sum) {
while (head != tail) {
var curr = head.key + tail.key;
if (curr == sum)
return true ;
else if (curr > sum)
tail = tail.left;
else
head = head.right;
}
return false ;
}
function isTripletPresent( root) {
if (root == null )
return false ;
head = null ;
tail = null ;
convertBSTtoDLL(root);
while ((head.right != tail) && (head.key < 0))
{
if (isPresentInDLL(head.right, tail,
-1 * head.key))
return true ;
else
head = head.right;
}
return false ;
}
function newNode(num) {
var temp = new node();
temp.key = num;
temp.left = temp.right = null ;
return temp;
}
function insert( root , key) {
if (root == null )
return newNode(key);
if (root.key > key)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return root;
}
var root = null ;
root = insert(root, 6);
root = insert(root, -13);
root = insert(root, 14);
root = insert(root, -8);
root = insert(root, 15);
root = insert(root, 13);
root = insert(root, 7);
if (isTripletPresent(root))
document.write( "Present" );
else
document.write( "Not Present" );
</script>
|
Note that the above solution modifies given BST.
Time Complexity: Time taken to convert BST to DLL is O(n) and time taken to find triplet in DLL is O(n^2).
Auxiliary Space: The auxiliary space is needed only for function call stack in recursive function convertBSTtoDLL(). Since given tree is balanced (height is O(Logn)), the number of functions in call stack will never be more than O(Logn).
We can also find triplet in same time and extra space without modifying the tree. See next post. The code discussed there can be used to find triplet also.
Last Updated :
20 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...