给你 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]
思路:对两棵二叉搜索树的所有数字按升序进行排序,二叉搜索树按中序遍历可以得到一个升序排序的数组,因此我们可以先对root1和root2进行中序遍历,得到各自的升序数组,然后用两个指针分别指向数组的下标,将更小的数先放入result中,若一个已经遍历完,另一个还有剩余,那就把另一个数组剩余的数字放入result。
代码(Python):
class Solution(object):
def getAllElements(self, root1, root2):
result1 = []
result2 = []
def traversal(root,result): #中序遍历
if not root:
return
traversal(root.left,result)
result.append(root.val)
traversal(root.right,result)
traversal(root1,result1) #得到root1的升序排序
traversal(root2,result2) #得到root2的升序排序
index1 = 0 #result1的下标
index2 = 0 #result2的下标
result = []
while index1 < len(result1) and index2 < len(result2): #两个数组更小的数字先放入result
if result1[index1] <= result2[index2]:
result.append(result1[index1])
index1 += 1
else:
result.append(result2[index2])
index2 += 1
if index1 < len(result1): #若result2遍历完了,result1还有剩余
for i in range(index1,len(result1)):
result.append(result1[i])
if index2 < len(result2): #若result1遍历完了,result2还有剩余
for i in range(index2,len(result2)):
result.append(result2[i])
return result