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

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

  顺序合并时间复杂度 O(N) ,远快于任何排序算法。

  JAVA:

public final List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
        List<Integer> list1 = new LinkedList<Integer>(), list2 = new LinkedList<Integer>();
        dfs(root1, list1);
        dfs(root2, list2);
        return combine(list1, list2);
    }

    private final List<Integer> combine(List<Integer> list1, List<Integer> list2) {
        int point1 = 0, point2 = 0, len1 = list1.size(), len2 = list2.size();
        List<Integer> reList = new LinkedList<Integer>();
        while (point1 < len1 && point2 < len2) {
            int val1 = list1.get(point1), val2 = list2.get(point2);
            if (val1 <= val2) {
                reList.add(val1);
                point1++;
            } else {
                reList.add(val2);
                point2++;
            }
        }
        if (point1 < len1) {
            for (int i = point1; i < len1; i++) reList.add(list1.get(i));
        }
        if (point2 < len2) {
            for (int i = point2; i < len2; i++) reList.add(list2.get(i));
        }
        return reList;
    }

    private final void dfs(TreeNode root, List<Integer> list) {
        if (root == null) return;
        dfs(root.left, list);
        list.add(root.val);
        dfs(root.right, list);
    }

  JS:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {number[]}
 */
var getAllElements = function (root1, root2) {
    let arr1 = [], arr2 = [];
    dfs(root1, arr1);
    dfs(root2, arr2);
    return combine(arr1, arr2);
};

var combine = (arr1, arr2) => {
    let len1 = arr1.length, len2 = arr2.length, point1 = 0, point2 = 0, reArr = [];
    while (point1 < len1 && point2 < len2) {
        let val1 = arr1[point1], val2 = arr2[point2];
        if (val1 <= val2) {
            reArr.push(val1);
            point1++;
        } else {
            reArr.push(val2);
            point2++;
        }
    }
    if (point1 < len1) for (let i = point1; i < len1; i++) reArr.push(arr1[i]);
    if (point2 < len2) for (let i = point2; i < len2; i++) reArr.push(arr2[i]);
    return reArr;
}

var dfs = (root, arr) => {
    if (!root) return;
    dfs(root.left, arr);
    arr.push(root.val);
    dfs(root.right, arr);
}

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

 

上一篇:【力扣】973. 最接近原点的 K 个点


下一篇:内置函数——hasattr() 函数