Find if there is a triplet in a Balanced BST that adds to zero
Last Updated : 23 Jul, 2025
Given a Balanced Binary Search Tree (BST), the task is to check if there is a triplet in the given BST with a sum equal to 0.
Example:
Input:
Output: True Explanation: 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 3 Sum – Triplet Sum in Array 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.
[Expected approach] Convert tree to DLL - O(n^2) Time and O(log n) Space
The approach involves first converting the given BST into a Doubly Linked List (DLL). Once the BST is converted, each node in the DLL is treated as the first element of a potential triplet. For each node, we search for a pair of nodes in the DLL whose sum equals the negative of the current node’s key. To find the pair, we can use the approach discussed in method 1 of Pair with given Sum (Two Sum) post. If such a pair is found, it indicates the presence of a triplet with a sum of zero. If no such triplet is found after iterating through all nodes, returns false.
Follow the steps below to solve the problem:
Convert the given Binary Search Tree (BST) into a Doubly Linked List (DLL) using in-order traversal, where left pointer acts as the previous and right pointer acts as the next pointer.
Iterate through each node of the DLL,treating it as the first element of a potential triplet.
For each node, search for a pair of nodes in the DLL (starting from the current node’s right) whose sum equals the negative value of the current node's key.
If such a triplet is found, return true. if no triplet is found after all iterations, return false.
Below is the implementation of the above approach:
C++
// C++ program to find triplets in a // BST that sum to 0.#include<bits/stdc++.h>usingnamespacestd;classNode{public:intkey;Node*left;Node*right;Node(intx){key=x;left=right=nullptr;}};// A function to convert given BST to a Doubly// Linked List (DLL).voidconvertBSTtoDLL(Node*root,Node*&head,Node*&tail){if(root==nullptr)return;// Recursively convert the left subtreeif(root->left)convertBSTtoDLL(root->left,head,tail);root->left=tail;// If tail is not null, then set the right of tail as root,// else the curr node is the head of the DLL.if(tail)(tail)->right=root;elsehead=root;tail=root;// Recursively convert the right subtreeif(root->right)convertBSTtoDLL(root->right,head,tail);}// This function returns true if there is a pair in the DLL with a// sum equal to the given sum.boolisPresentInDLL(Node*head,Node*tail,intsum){while(head!=tail){intcurrSum=head->key+tail->key;if(currSum==sum)returntrue;elseif(currSum>sum)tail=tail->left;elsehead=head->right;}returnfalse;}// The main function that returns true if there // is a 0-sum triplet in the BST, otherwise false.boolisTripletPresent(Node*root){// Check if the BST is emptyif(root==nullptr)returnfalse;// Convert the given BST to a Doubly Linked ListNode*head=nullptr;Node*tail=nullptr;convertBSTtoDLL(root,head,tail);// Now, iterate through every node and find if there is// a pair with a sum equal to -1 * head->keyNode*curr=head;while(curr!=nullptr&&curr->right!=nullptr){// If a pair with sum equal to -1 * curr->key is// found, return trueif(isPresentInDLL(curr->right,tail,-1*curr->key))returntrue;curr=curr->right;}returnfalse;}intmain(){// Construct the BST// 6// / \ // -13 14// \ / \ // -8 13 15// /// 7Node*root=newNode(6);root->left=newNode(-13);root->right=newNode(14);root->left->right=newNode(-8);root->right->left=newNode(13);root->right->right=newNode(15);root->right->left->left=newNode(7);if(isTripletPresent(root))cout<<"true";elsecout<<"false";return0;}
Java
// Java program to find triplets in a // BST that sum to 0.classNode{intkey;Nodeleft,right;Node(intx){key=x;left=right=null;}}classGfG{// A function to convert given BST to a Doubly // Linked List (DLL).staticvoidconvertBSTtoDLL(Noderoot,Node[]head,Node[]tail){if(root==null){return;}// Recursively convert the left subtreeif(root.left!=null)convertBSTtoDLL(root.left,head,tail);root.left=tail[0];// If tail is not null, then set the right of tail as root,// else the current node is the head of the DLL.if(tail[0]!=null)tail[0].right=root;elsehead[0]=root;tail[0]=root;// Recursively convert the right subtreeif(root.right!=null)convertBSTtoDLL(root.right,head,tail);}// This function returns true if there is a pair// in the DLL with a sum equal to the given sum.staticbooleanisPresentInDLL(Nodehead,Nodetail,intsum){while(head!=tail){intcurrSum=head.key+tail.key;if(currSum==sum)returntrue;elseif(currSum>sum)tail=tail.left;elsehead=head.right;}returnfalse;}// The main function that returns true if there // is a 0-sum triplet in the BST, otherwise false.staticbooleanisTripletPresent(Noderoot){// Check if the BST is emptyif(root==null)returnfalse;// Convert the given BST to a Doubly // Linked ListNodehead=null;Nodetail=null;Node[]headRef=newNode[1];Node[]tailRef=newNode[1];convertBSTtoDLL(root,headRef,tailRef);head=headRef[0];tail=tailRef[0];// Now, iterate through every node and find if// there is a pair with a sum equal to -1 * head->keyNodecurr=head;while(curr!=null&&curr.right!=null){// If a pair with sum equal to -1 * curr->key is found,// return trueif(isPresentInDLL(curr.right,tail,-1*curr.key))returntrue;curr=curr.right;}returnfalse;}publicstaticvoidmain(String[]args){// Construct the BST// 6// / \// -13 14// \ / \// -8 13 15// / // 7Noderoot=newNode(6);root.left=newNode(-13);root.right=newNode(14);root.left.right=newNode(-8);root.right.left=newNode(13);root.right.right=newNode(15);root.right.left.left=newNode(7);if(isTripletPresent(root))System.out.println("true");elseSystem.out.println("false");}}
Python
# Python program to find triplets in # a BST that sum to 0.classNode:def__init__(self,x):self.key=xself.left=Noneself.right=None# A function to convert given BST to a # Doubly Linked List (DLL).defconvertBSTtoDLL(root,head,tail):ifrootisNone:return# Recursively convert the left subtreeifroot.left:convertBSTtoDLL(root.left,head,tail)root.left=tail[0]# If tail is not null, then set the right of tail as root,# else the current node is the head of the DLL.iftail[0]:tail[0].right=rootelse:head[0]=roottail[0]=root# Recursively convert the right subtreeifroot.right:convertBSTtoDLL(root.right,head,tail)# This function returns true if there is a pair in # the DLL with a sum equal to the given sum.defisPresentInDLL(head,tail,sum_val):whilehead!=tail:curr_sum=head.key+tail.keyifcurr_sum==sum_val:returnTrueelifcurr_sum>sum_val:tail=tail.leftelse:head=head.rightreturnFalse# The main function that returns true if there is a # 0-sum triplet in the BST, otherwise false.defisTripletPresent(root):# Check if the BST is emptyifrootisNone:returnFalse# Convert the given BST to a Doubly# Linked Listhead=[None]tail=[None]convertBSTtoDLL(root,head,tail)# Now, iterate through every node and find if there is # a pair with a sum equal to -1 * head.keycurr=head[0]whilecurrandcurr.right:# If a pair with sum equal to -1 * curr.key is# found, return trueifisPresentInDLL(curr.right,tail[0],-1*curr.key):returnTruecurr=curr.rightreturnFalseif__name__=='__main__':# Construct the BST# 6# / \# -13 14# \ / \# -8 13 15# /# 7root=Node(6)root.left=Node(-13)root.right=Node(14)root.left.right=Node(-8)root.right.left=Node(13)root.right.right=Node(15)root.right.left.left=Node(7)ifisTripletPresent(root):print("true")else:print("false")
C#
// C# program to find triplets in// a BST that sum to 0.usingSystem;classNode{publicintkey;publicNodeleft,right;publicNode(intx){key=x;left=right=null;}}classGfG{// A function to convert the given BST to a// Doubly Linked List (DLL).staticvoidConvertBSTtoDLL(Noderoot,refNodehead,refNodetail){if(root==null){return;}// Recursively convert the left subtreeif(root.left!=null)ConvertBSTtoDLL(root.left,refhead,reftail);root.left=tail;// If tail is not null, then set the right of tail as root,// else the current node is the head of the DLL.if(tail!=null)tail.right=root;elsehead=root;tail=root;// Recursively convert the right subtreeif(root.right!=null)ConvertBSTtoDLL(root.right,refhead,reftail);}// This function returns true if there is a pair// in the DLL with a sum equal to the given sum.staticboolIsPresentInDLL(Nodehead,Nodetail,intsum){while(head!=tail){intcurrSum=head.key+tail.key;if(currSum==sum)returntrue;elseif(currSum>sum)tail=tail.left;elsehead=head.right;}returnfalse;}// The main function that returns true if there is a // 0-sum triplet in the BST, otherwise false.staticboolIsTripletPresent(Noderoot){// Check if the BST is emptyif(root==null)returnfalse;// Convert the given BST to a Doubly Linked ListNodehead=null,tail=null;ConvertBSTtoDLL(root,refhead,reftail);// Now, iterate through every node and find if there // is a pair with a sum equal to -1 * curr.keyNodecurr=head;while(curr!=null&&curr.right!=null){// If a pair with sum equal to -1 * curr.key is found, // return trueif(IsPresentInDLL(curr.right,tail,-1*curr.key))returntrue;curr=curr.right;}returnfalse;}staticvoidMain(){// Construct the BST// 6// / \// -13 14// \ / \// -8 13 15// /// 7Noderoot=newNode(6);root.left=newNode(-13);root.right=newNode(14);root.left.right=newNode(-8);root.right.left=newNode(13);root.right.right=newNode(15);root.right.left.left=newNode(7);if(IsTripletPresent(root))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Javascript program to find triplets in// a BST that sum to 0.classNode{constructor(key){this.key=key;this.left=null;this.right=null;}}// A function to convert the given BST to a // Doubly Linked List (DLL).functionconvertBSTtoDLL(root,head,tail){if(root===null)return;// Recursively convert the left subtreeif(root.left!==null)convertBSTtoDLL(root.left,head,tail);root.left=tail.node;// If tail is not null, then set the right of tail as root,// else the current node is the head of the DLL.if(tail.node!==null){tail.node.right=root;}else{head.node=root;}tail.node=root;// Recursively convert the right subtreeif(root.right!==null)convertBSTtoDLL(root.right,head,tail);}// This function returns true if there is a pair // in the DLL with a sum equal to the given sum.functionisPresentInDLL(head,tail,sum){while(head!==tail){letcurrSum=head.key+tail.key;if(currSum===sum){returntrue;}elseif(currSum>sum){tail=tail.left;}else{head=head.right;}}returnfalse;}// The main function that returns true if there is a // 0-sum triplet in the BST, otherwise false.functionisTripletPresent(root){// Check if the BST is emptyif(root===null)returnfalse;// Convert the given BST to a Doubly Linked Listlethead={node:null};lettail={node:null};convertBSTtoDLL(root,head,tail);// Now, iterate through every node and find if there is// a pair with a sum equal to -1 * curr.keyletcurr=head.node;while(curr!==null&&curr.right!==null){// If a pair with sum equal to -1 * curr.key// is found, return trueif(isPresentInDLL(curr.right,tail.node,-1*curr.key)){returntrue;}curr=curr.right;}returnfalse;}// Construct the BST// 6// / \// -13 14// \ / \// -8 13 15// /// 7letroot=newNode(6);root.left=newNode(-13);root.right=newNode(14);root.left.right=newNode(-8);root.right.left=newNode(13);root.right.right=newNode(15);root.right.left.left=newNode(7);if(isTripletPresent(root)){console.log("true");}else{console.log("false");}
Output
true
We can also find triplet in same time and extra space without modifying the tree. See Find a pair with given sum in a Balanced BST post. The code discussed there can be used to find triplet also.