Given the root of a Binary Search Tree (BST) of size n and an integer target, determine whether there exists a pair of distinct nodes in the BST such that the sum of their values is equal to the given target. Return true if such a pair exists; otherwise, return false.
Example:
Input: root = [7, 3, 8, 2, 4, N, 9], target = 12 Output: true Explanation: In the given binary tree, there are two nodes (3 and 9) that add up to 12.
[Naive Approach] Check Complement for Every Node - O(nΒ²) Time and O(h) Space
The idea is to traverse the BST and, for each node, search for its complement (target - node value) in the BST. If the complement exists in a different node, return true.
Output
true
[Better Approach 1] Using Hash Set - O(n) time and O(n) space
The idea of this approach is to use a Hash Set to store the values of nodes visited during a traversal of the BST. While traversing each node, we check whether the complement value (target - current node value) already exists in the set. If it exists, it means a valid pair of distinct nodes has been found whose sum is equal to the target, and we return true. Otherwise, we insert the current nodeβs value into the set and continue the traversal.
Output
true
[Expected Approach 2] Using Inorder Traversal and Two Pointers - O(n) time and O(n) space
The idea of this approach is based on the property of a Binary Search Tree (BST), where an inorder traversal always produces elements in sorted order. We first perform an inorder traversal of the BST and store all node values in an auxiliary array. Since the BST inorder is sorted, the resulting array will also be sorted. Once we have the sorted array, we apply the two-pointer technique to find whether there exists a pair of elements whose sum is equal to the given target.
Perform inorder traversal of the BST
Store all node values in an array, which becomes sorted due to BST inorder property
Initialize two pointers: left = 0 and right = n - 1
While left < right, compute currentSum = arr[left] + arr[right]
If currentSum == target, return true
If currentSum < target, increment left pointer
If currentSum > target, decrement right pointer
If no valid pair is found after traversal, return false
Consider the BST: root = [7, 3, 8, 2, 4, N, 9], target = 12