Leetcode #1214: Two Sum BSTs
In this guide, we solve Leetcode #1214 Two Sum BSTs in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Stack, Tree, Depth-First Search, Binary Search Tree, Two Pointers, Binary Search, Binary Tree
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
Output: true
Explanation: 2 and 3 sum up to 5.
Python Solution
# 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 dfs(root: Optional[TreeNode], i: int):
if root is None:
return
dfs(root.left, i)
nums[i].append(root.val)
dfs(root.right, i)
nums = [[], []]
dfs(root1, 0)
dfs(root2, 1)
i, j = 0, len(nums[1]) - 1
while i < len(nums[0]) and ~j:
x = nums[0][i] + nums[1][j]
if x == target:
return True
if x < target:
i += 1
else:
j -= 1
return False
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.