Javatpoint Logo
Javatpoint Logo

Find if there is a triplet in a balanced bst that adds to zero

Problem Statement:

Given a balanced (height balanced) binary search tree and the task is to find whether there exists a triplet (3 elements) that sum up to 0 and if present return present else not present



{-13,  6, 7}

The straightforward approach involves examining every triplet within the Binary Search Tree (BST) and verifying whether the sum equals zero. This method carries a time complexity of O(n^3).

An improved strategy entails generating an auxiliary array to store the Inorder traversal of the Binary Search Tree (BST). This array is guaranteed to be sorted, as the Inorder traversal of a BST consistently yields data in sorted order.

Better version

The provided solution operates in O(n^2) time complexity and utilizes O(Logn) additional space:

  1. Transform the given Binary Search Tree (BST) into a Doubly Linked List (DLL).
  2. Iterate through each node of the DLL. If the node's key is negative, search for a pair within the DLL whose sum equals the key of the current node multiplied by -1.

Java Implementation:


Find if there is a triplet in a balanced bst that adds to zero

Time Complexity: O(n^2)

Space Complexity: O(log(n))

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA