1 class Solution: 2 def midOrder(self,root,l): 3 if root != None: 4 if root.left != None: 5 self.midOrder(root.left,l) 6 l.append(root.val) 7 if root.right != None: 8 self.midOrder(root.right,l) 9 10 def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: 11 l1,l2 = [],[] 12 self.midOrder(root1,l1) 13 self.midOrder(root2,l2) 14 res = [] 15 n1,n2 = len(l1),len(l2) 16 i,j = 0,0 17 while i < n1 and j < n2: 18 if l1[i] <= l2[j]: 19 res.append(l1[i]) 20 i += 1 21 else: 22 res.append(l2[j]) 23 j += 1 24 if i < n1: 25 res += l1[i:] 26 elif j < n2: 27 res += l2[j:] 28 return res
分别使用中序遍历两颗二叉搜索树,得到两个有序列表。再将两个数组合并为一个有序数组。