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
Two Sum BSTs: Library Book SearchLibrary Section 1 (BST 1)Books sorted by ID3579Library Section 2 (BST 2)Books sorted by ID1468Target Sum = 10Goal: Find one book from each section whose IDs sum to 10Example: Book ID 3 (Section 1) + Book ID 7 (Section 2) = 10 โœ“Three Approaches Comparison๐Ÿ”จ Brute ForceCheck every book insection 1 against everybook in section 2O(m ร— n)Very slow!๐Ÿ“š Hash TableMake index of section 1,then check section 2for complementsO(m + n)Fast & simple๐Ÿ‘‰๐Ÿ‘ˆ Two PointersTwo librarians scanfrom opposite endsof sorted listsO(m + n)Optimal!
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
24.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen