0
点赞
收藏
分享

微信扫一扫

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

unadlib 2022-05-01 阅读 70

题目

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

示例

在这里插入图片描述
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]

在这里插入图片描述
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]

方法1:模拟

Java实现
class Solution {
    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        bl(root1, list1);
        bl(root2, list2);

        List<Integer> res = new ArrayList<>();
        int l = 0, r = 0;
        while (l < list1.size() && r < list2.size()) {
            if (list1.get(l) <= list2.get(r)) {
                res.add(list1.get(l++));
            } else {
                res.add(list2.get(r++));
            }
        }

        while (l < list1.size()) res.add(list1.get(l++));
        while (r < list2.size()) res.add(list2.get(r++));
        return res;
    }

    public void bl(TreeNode root, List<Integer> list) {
        if (root == null) return;

        bl(root.left, list);
        list.add(root.val);
        bl(root.right, list);
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论