GFG App
Open App
Browser
Continue

# 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

1. Convert given BST to Doubly Linked List (DLL)
2. 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:

## Javascript



Output

Present

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.

My Personal Notes arrow_drop_up