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

For example, consider the following BST. If the given sum is 14, the pair is (8, 6).

 
Pair with the given sum in the BST

Practice this problem

We can easily solve this problem by using hashing. The idea is to traverse the tree in an inorder fashion and insert every node’s value into a set. Also check if, for any node, the difference between the given sum and node’s value is found in the set, then the pair with the given sum exists in the tree.

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

C++


Download  Run Code

Output:

Pair found (12, 16)

Java


Download  Run Code

Output:

Pair found (12, 16)

Python


Download  Run Code

Output:

Pair found (12, 16)

The time complexity of the above solution is O(n), 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 triplet with the given sum in a BST