1305. 两棵二叉搜索树中的所有元素

给你 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
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值