题目
给你 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
思路
根据二叉搜索树的性质,中序遍历可以得到一个升序数组,将两个二叉搜索树分别中序遍历,在两个数组都升序的情况下再使用归并排序即可解决
题解
# 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: TreeNode, root2: TreeNode) -> List[int]:
res1 = self.dfs(root1, [])
res2 = self.dfs(root2, [])
if res1 is None or res2 is None:
return res1 if res1 is not None else res2
res = []
left,right = 0, 0
while left < len(res1) and right < len(res2):
if res1[left] <= res2[right]:
res.append(res1[left])
left += 1
else:
res.append(res2[right])
right += 1
if left <= len(res1) -1:
for i in range(left, len(res1)):
res.append(res1[i])
if right <= len(res2)-1:
for i in range(right, len(res2)):
res.append(res2[i])
return res
def dfs(self, root, res):
if root is None:
return
self.dfs(root.left, res)
res.append(root.val)
self.dfs(root.right, res)
return res