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
Understanding the Visualization
1
Two Organized Library Sections
Each BST represents a library section with books sorted by ID numbers
2
Brute Force: Check Every Pair
Walk through every book in section 1, checking it against every book in section 2
3
Hash Table: Create Index First
Make a quick-lookup index of all IDs in section 1, then check section 2 for complements
4
Two Pointers: Smart Scanning
Line up books from both sections in order, use two librarians scanning from opposite ends
Key Takeaway
๐ฏ Key Insight: Converting BSTs to sorted arrays unlocks the powerful two-pointers technique, giving us optimal O(m + n) performance while maintaining clear, intuitive logic.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code