Two Sum BSTs Problem
Description
LeetCode Problem 1214.
Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.
Example 1:

Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
Output: true
Explanation: 2 and 3 sum up to 5.
Example 2:

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
Output: false
Constraints:
- The number of nodes in each tree is in the range
[1, 5000]. -10^9 <= Node.val, target <= 10^9
Solution
Approach: In-order Traversal + Two Pointers
An in-order traversal of a binary search tree visits its values in increasing order. Doing that for both trees turns the problem into the classic one: two sorted arrays a and b, is there an a[i] + b[j] == target?
Put i at the start of a (its smallest value) and j at the end of b (its largest), and compare a[i] + b[j] with target:
- Equal: we found a pair.
- Too small:
a[i]is too small to pair withb[j], and every value ofbstill left is smaller, soa[i]can never work. Moveiright. - Too large: by the same argument
b[j]can never work. Movejleft.
Each step throws away one value for good, so the scan ends after at most m + n steps.
Two details. The traversal is written with an explicit stack, because a tree of 5000 nodes can be a single chain, and recursing that deep can overflow the stack in Java or JavaScript. And in Java and C++ the sum is taken in 64 bits: two values near 109 add up to about 2 · 109, which overflows a 32-bit int and could even wrap around to equal target.
Complexity: O(m + n) time and O(m + n) extra space for the two value lists, where m and n are the sizes of the trees.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def twoSumBSTs(self, root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool:
def inorder(root: Optional[TreeNode]) -> List[int]:
# Iterative, so a tree shaped like a long chain does not overflow the stack.
vals, stack = [], []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
vals.append(root.val)
root = root.right
return vals
a, b = inorder(root1), inorder(root2) # both sorted ascending
i, j = 0, len(b) - 1
while i < len(a) and j >= 0:
s = a[i] + b[j]
if s == target:
return True
if s < target:
i += 1 # need a bigger sum
else:
j -= 1 # need a smaller sum
return False