Problem Description
Given the roots of two binary search trees, root1 and root2, determine if there exists a node from the first tree and a node from the second tree whose values add up exactly to a given integer target.
Key Insights
- Traverse the first tree to collect all node values.
- Traverse the second tree to check for each node if the complement (target - current node value) exists in the first tree’s values.
- Using a hash set for the first tree values allows efficient O(1) lookups.
- The BST property is not essential for the hash set solution, but can be exploited if using iterator techniques for a two-pointer approach.
Space and Time Complexity
Time Complexity: O(n + m) where n and m are the number of nodes in the first and second trees respectively. Space Complexity: O(n) for storing the node values from the first tree (in worst-case scenario).
Solution
We perform a DFS (or any tree traversal) on the first BST to collect all its values in a hash set. Then, we traverse the second BST and for each node, we calculate the complement (target - node value) and check whether this complement exists in the hash set. If we find such a pair, we return true. If no such pair exists after traversing the second tree completely, we return false.
This approach is straightforward and leverages extra space (the set) for constant time lookups, yielding an overall linear time complexity relative to the number of nodes.