February 21, 2025 |3.1K Views

Pair with given Sum in BST

Explore Courseexplore course icon
Description
Discussion

In this video, we will discuss two approaches to solve the problem of finding a pair of nodes in a Binary Search Tree (BST) such that their sum equals a given target. The first approach uses a HashSet to track the values we’ve encountered during a depth-first search (DFS). As we traverse the tree, for each node, we check if the complement of the current node’s value (i.e., target - node->value) exists in the set. If it does, we return true; otherwise, we add the current node’s value to the set. This method runs in O(n) time and uses O(n) space, where n is the number of nodes in the BST.

The second approach utilizes the properties of the BST and the two-pointer technique. We first perform an in-order traversal to create a sorted array of the BST’s values. Then, we apply the two-pointer technique to find a pair of integers that add up to the target sum. This approach also runs in O(n) time and uses O(n) space, as it requires storing the in-order traversal in an auxiliary array. Watch the video to understand both methods in detail and see how they can efficiently solve the problem of finding a pair of nodes with a given sum in a BST.

For more details, please go through - Two Sum in BST – Pair with given sum