Problem Description
Given the root of a binary search tree and an integer k, determine if there exist two different nodes in the BST such that their values add up to k.
Key Insights
- Utilize the BST property to traverse the tree while checking for the complementary value (k - current node's value).
- A hash set can be used to store seen node values which facilitates constant time lookups.
- Alternatively, an in-order traversal converts the BST into a sorted array, allowing a two-pointer approach.
- The recursive DFS solution is both intuitive and easy to implement for this problem.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes, since each node is visited once. Space Complexity: O(n) in the worst case due to the extra space used by the hash set (or recursion stack in the worst-case scenario of an unbalanced tree).
Solution
The solution uses a depth-first search (DFS) traversal while maintaining a hash set to remember the values of visited nodes. For each node, check if k minus the node's value exists in the hash set. If it does, return true. Otherwise, add the node's value to the set and continue the DFS on both the left and right children. This approach efficiently finds a pair of nodes that sum up to k without needing to traverse the tree more than once.