代码随想录算法训练营第十九天 | 654.最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树

66 阅读1分钟

654.最大二叉树

617.合并二叉树

700.二叉搜索树中的搜索

98.验证二叉搜索树

654. 最大二叉树

思路:左闭右闭区间

var constructMaximumBinaryTree = function(nums) {
    const traverse = (start, end) => {
        if (start > end) return null;

        const subNums = nums.slice(start, end+1);
        const maxVal = Math.max(...subNums);
        const maxIdx = nums.findIndex((v) => v === maxVal);
        const root = new TreeNode(maxVal);

        root.left = traverse(start, maxIdx - 1);
        root.right = traverse(maxIdx + 1, end);
        return root;
    }

    return traverse(0, nums.length - 1);
};

617. 合并二叉树

关键:基于一棵树,将另一棵树的节点合并到这棵树上

var mergeTrees = function(root1, root2) {
    if (!root1 && !root2)   return null;
    if (!root1 && root2)    return root2;
    if (root1 && !root2)    return root1;

    const q = []; q.push(root1); q.push(root2);

    while (q.length > 0) {
        const node1 = q.shift();
        const node2 = q.shift();

        node1.val += node2.val;

        if (node1.left && node2.left) {
            q.push(node1.left);
            q.push(node2.left);
        }
        if (node1.right && node2.right) {
            q.push(node1.right);
            q.push(node2.right);
        }

        if (!node1.left && node2.left) {
            node1.left = node2.left;
        }
        if (!node1.right && node2.right) {
            node1.right = node2.right;
        }
    }

    return root1;
};

700. 二叉搜索树中的搜索

var searchBST = function(root, val) {
    const traverse = (node) => {
        if (!node)  return null;

        if (node.val > val) return traverse(node.left);
        if (node.val < val) return traverse(node.right);
        return node;
    }

    return traverse(root);
};

98. 验证二叉搜索树

var isValidBST = function(root) {
    let preNode = null;

    const traverse = (node) => {
        if (!node)  return true;

        const validL = traverse(node.left);
        if (preNode && preNode.val >= node.val)    return false;
        preNode = node;
        return validL && traverse(node.right);
    }

    return traverse(root);  
};