Prepin
Log in

Locate a pair that yields a specified sum in a binary search tree (BST).

Approach / Explanation

This task requires you to create a function that can find a pair of elements in a Binary Search Tree (BST) that sums up to a specified value. Understanding the characteristics of a BST will be crucial for efficiently addressing this challenge. Important points to keep in mind: A Binary Search Tree is structured so that all values in the left subtree of a node are less than the node's value, while all values in the right subtree are greater. Assume that the values are unique integers. If there is no valid pair in the BST, the function should return None or a similar value. A binary search tree can be traversed either in an in-order manner (resulting in ascending order of values) or in reverse in-order (yielding descending order). The key to efficiently solving this problem lies in the method of traversing the BST and recognizing the properties of sorted arrays.

Suggested Answer

One method to tackle this problem is by employing In-Order and Reverse In-Order traversal. Begin by setting up two pointers: one at the smallest element (far left) and the other at the largest (far right). Sum these two values. If the sum is less than the target, move the left pointer to the right (to a larger value). If the sum exceeds the target, shift the right pointer to the left (to a smaller value). Continue this process until the pointers meet. To implement this, perform an in-order traversal to collect values in ascending order and store them in one list. Next, execute a reverse in-order traversal to gather values in descending order and save them in a second list. Then, apply the aforementioned approach on these two lists.

Alternative Answer

Another method involves utilizing a HashSet. This method is based on the idea that if we aim to find a pair that sums to 'x' and we are currently at 'y', we can check if 'x-y' has already been encountered. If it has, we've found a pair; if not, we add 'y' to our set and continue. Begin an in-order traversal of the BST. For each node, verify whether the target sum minus the node's value is present in the HashSet. If it is found, this indicates that the current node value and (target sum - node value) form a pair that adds up to the target sum. If it is not found, add the node's value to the HashSet and proceed to the next node. This approach offers the benefit of reduced memory usage compared to the first method, as it does not require storing all elements of the BST.

Question Details

Difficulty & Category

Medium
data structures

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.