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
目录
相关文章
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
1天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
6天前
|
算法
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
代码随想录算法训练营第五十七天 | LeetCode 739. 每日温度、496. 下一个更大元素 I
11 3
|
10天前
|
算法
【力扣】169. 多数元素
【力扣】169. 多数元素
|
10天前
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
|
1月前
|
存储 JavaScript
leetcode82. 删除排序链表中的重复元素 II
leetcode82. 删除排序链表中的重复元素 II
22 0
|
1月前
leetcode83. 删除排序链表中的重复元素
leetcode83. 删除排序链表中的重复元素
10 0
|
1月前
|
算法 搜索推荐
LeetCode刷题---215. 数组中的第K个最大元素(双指针,快速选择)
LeetCode刷题---215. 数组中的第K个最大元素(双指针,快速选择)
|
28天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记