LeetCode每日一题——1305. 两棵二叉搜索树中的所有元素

简介: 给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。

题目

给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。

示例

示例 1:

2345_image_file_copy_1.jpg

输入:root1 = [2,1,4], root2 = [1,0,3]

输出:[0,1,1,2,3,4]


示例 2:

2345_image_file_copy_2.jpg

输入: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
目录
相关文章
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
153 1
|
7月前
|
机器学习/深度学习 存储 算法
【LeetCode 热题100】347:前 K 个高频元素(详细解析)(Go语言版)
这篇文章详细解析了力扣热题 347——前 K 个高频元素的三种解法:哈希表+小顶堆、哈希表+快速排序和哈希表+桶排序。每种方法都附有清晰的思路讲解和 Go 语言代码实现。小顶堆方法时间复杂度为 O(n log k),适合处理大规模数据;快速排序方法时间复杂度为 O(n log n),适用于数据量较小的场景;桶排序方法在特定条件下能达到线性时间复杂度 O(n)。文章通过对比分析,帮助读者根据实际需求选择最优解法,并提供了完整的代码示例,是一篇非常实用的算法学习资料。
459 90
【LeetCode 27】347.前k个高频元素
【LeetCode 27】347.前k个高频元素
129 0
【LeetCode 45】701.二叉搜索树中的插入操作
【LeetCode 45】701.二叉搜索树中的插入操作
91 1
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
101 1
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
124 0
【LeetCode 47】669.修剪二叉搜索树
【LeetCode 47】669.修剪二叉搜索树
77 0
【LeetCode 46】450.删除二叉搜索树的节点
【LeetCode 46】450.删除二叉搜索树的节点
148 0
【LeetCode 42】501.二叉搜索树中的众数
【LeetCode 42】501.二叉搜索树中的众数
100 0
【LeetCode 41】530.二叉搜索树的最小绝对差
【LeetCode 41】530.二叉搜索树的最小绝对差
101 0

热门文章

最新文章