VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-if-there-is-a-triplet-in-bst-that-adds-to-0/

⇱ Find if there is a triplet in a Balanced BST that adds to zero - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 Find-if-there-is-a-triplet-in-a-Balanced-BST-that-adds-to-zero

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).

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:  


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.

Comment
Article Tags: