Two Sum BSTs — LeetCode 1214 Python Solution
- Problem
- #1214
- Pattern
- Stack
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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
- 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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(m + n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1214. Two Sum BSTs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1214. Two Sum BSTs?
- LeetCode 1214. Two Sum BSTs is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1214. Two Sum BSTs?
- The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 1214. Two Sum BSTs?
- The Python solution on this page uses O(m + n) auxiliary space.
- What topics does LeetCode 1214. Two Sum BSTs cover?
- LeetCode 1214. Two Sum BSTs is tagged Stack, Tree, Depth-First Search, Binary Search Tree, Two Pointers, Binary Search and Binary Tree on LeetCode.
- Is LeetCode 1214. Two Sum BSTs a premium problem?
- Yes. LeetCode 1214. Two Sum BSTs is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.