Two Sum BSTs - Problem
You are given the roots of two binary search trees, root1 and root2. Your task is to determine if there exists a pair of nodes - one from each tree - whose values sum up to a given target integer.
Return true if such a pair exists, otherwise return false.
Example: If the first BST contains values [2, 1, 4] and the second BST contains values [1, 0, 3], and the target is 5, then we can find nodes with values 2 (from first tree) and 3 (from second tree) that sum to 5.
This problem leverages the sorted property of BSTs to find efficient solutions beyond the naive approach of checking all possible pairs.
Input & Output
example_1.py — Basic Case
$
Input:
root1 = [2,1,4], root2 = [1,0,3], target = 5
›
Output:
true
💡 Note:
2 and 3 sum up to 5. Node with value 2 is from first tree, node with value 3 is from second tree.
example_2.py — No Valid Pair
$
Input:
root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
›
Output:
false
💡 Note:
No pair of nodes from the two trees sum up to 18. The maximum possible sum would be 10 + 7 = 17.
example_3.py — Single Node Trees
$
Input:
root1 = [1], root2 = [2], target = 3
›
Output:
true
💡 Note:
The only nodes from each tree are 1 and 2, which sum to exactly 3.
Constraints
- The number of nodes in each tree is in the range [1, 5000]
- -103 ≤ Node.val ≤ 103
- -104 ≤ target ≤ 104
- Both input trees are valid binary search trees
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code