Given a binary search tree, find a triplet with a given sum present in it.

For example, consider the following BST. If the given sum is 20, the triplet is (-40, 10, 50).

 
BST

Practice this problem

A simple solution is to traverse the BST in an inorder fashion and store all encountered nodes in an auxiliary array. This array would be already sorted since inorder traversal visits the nodes in increasing order of their values. Then for each element A[i] in the array A, check if the triplet is formed by A[i] and a pair from subarray A[i+1…n-1].

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

Java


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

Python


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

The time complexity of the above solution is O(n2), where n is the size of the BST. The auxiliary space required by the program is O(n) for storing BST keys and for call stack.

 
We can avoid the extra space used for storing BST keys if we are allowed to modify the BST. The idea is to convert the given BST into a sorted doubly linked list and follow a similar routine to find a triplet as seen in the previous approach.

C++


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

Java


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

Python


Download  Run Code

Output:

Triplet found: (-40, 10, 50)

The time complexity of the above solution is O(n2), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.

 
Also See:

Find a pair with the given sum in a BST