给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。
方法1:先序遍历(或者其他方式)+sort 排序
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
ans=[]
def dfs(root):
nonlocal ans
if root:
ans.append(root.val)
dfs(root.left)
dfs(root.right)
dfs(root1)
dfs(root2)
ans.sort()
return ans
方法2:中序遍历 + 归并排序 (方法2比方法1还慢)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def dfs(root):
nonlocal ans
if root:
dfs(root.left)
ans.append(root.val)
dfs(root.right)
else:
return
ans=[]
dfs(root1)
list1=ans
ans=[]
dfs(root2)
list2=ans
stack=[]
i=0
j=0
while i<len(list1) and j<len(list2):
if list1[i]<list2[j]:
stack.append(list1[i])
i=i+1
elif list1[i]>list2[j]:
stack.append(list2[j])
j=j+1
else:
stack.append(list2[j])
stack.append(list1[i])
i=i+1
j=j+1
if i==len(list1) and j!=len(list2):
stack=stack+list2[j:]
elif i!=len(list1) and j==len(list2):
stack=stack+list1[i:]
return stack