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 - Hash Set Approach INPUT BST 1 (root1) 2 1 4 BST 2 (root2) 1 0 3 root1 = [2,1,4] root2 = [1,0,3] target = 5 ALGORITHM STEPS 1 Build Hash Set Traverse BST1, store values HashSet: {1, 2, 4} 2 Traverse BST2 For each node, calculate complement 3 Check Complement complement = target - node.val node=1: 5-1=4 in set? OK! node=0: 5-0=5 in set? No node=3: 5-3=2 in set? OK! 4 Found Match! 1 + 4 = 5 (target) Pair: (4, 1) sum = 5 FINAL RESULT Matching Pair Found 4 from BST1 + 1 from BST2 = 5 Output: true Pair exists! OK - Valid Pair Key Insight: Use a HashSet to store all values from BST1. Then traverse BST2 and check if (target - current_value) exists in the set. This converts O(n*m) brute force into O(n+m) time with O(n) space. Alternative: Two-pointer approach with in-order traversal uses O(h1+h2) space where h = tree height. TutorialsPoint - Two Sum BSTs | Hash Set Approach
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