LeetCode 题解工作台
两棵二叉搜索树中的所有元素
给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。. 示例 1: 输入: root1 = [2,1,4], root2 = [1,0,3] 输出: [0,1,1,2,3,4] 示例 2: 输入: root1 = [1,null,8]…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
由于两棵树都是二叉搜索树,所以我们可以通过中序遍历得到两棵树的节点值序列 和 ,然后使用双指针归并两个有序数组,得到最终的答案。 时间复杂度 ,空间复杂度 。其中 和 分别是两棵树的节点数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:

输入:root1 = [2,1,4], root2 = [1,0,3] 输出:[0,1,1,2,3,4]
示例 2:

输入:root1 = [1,null,8], root2 = [8,1] 输出:[1,1,8,8]
提示:
- 每棵树的节点数在
[0, 5000]范围内 -105 <= Node.val <= 105
解题思路
方法一:DFS + 归并
由于两棵树都是二叉搜索树,所以我们可以通过中序遍历得到两棵树的节点值序列 和 ,然后使用双指针归并两个有序数组,得到最终的答案。
时间复杂度 ,空间复杂度 。其中 和 分别是两棵树的节点数。
# 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 getAllElements(
self, root1: Optional[TreeNode], root2: Optional[TreeNode]
) -> List[int]:
def dfs(root: Optional[TreeNode], nums: List[int]) -> int:
if root is None:
return
dfs(root.left, nums)
nums.append(root.val)
dfs(root.right, nums)
a, b = [], []
dfs(root1, a)
dfs(root2, b)
m, n = len(a), len(b)
i = j = 0
ans = []
while i < m and j < n:
if a[i] <= b[j]:
ans.append(a[i])
i += 1
else:
ans.append(b[j])
j += 1
while i < m:
ans.append(a[i])
i += 1
while j < n:
ans.append(b[j])
j += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently merge two sorted lists using a two-pointer technique?
- question_mark
Does the candidate understand the trade-offs between DFS and iterative approaches?
- question_mark
How well does the candidate handle recursion or stack-based tree traversal methods?
常见陷阱
外企场景- error
Not using in-order traversal, which results in an unnecessary sort step at the end.
- error
Ignoring the fact that both trees are already sorted, leading to inefficient solutions.
- error
Overcomplicating the solution by not merging the two trees while traversing.
进阶变体
外企场景- arrow_right_alt
What if one of the trees is empty?
- arrow_right_alt
How would the solution change if the trees were not binary search trees?
- arrow_right_alt
Can the problem be solved without using extra space?