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

90 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情🚀🚀

654. 最大二叉树 - 力扣(LeetCode)

image.png

递归

var constructMaximumBinaryTree = function (nums) {
    const BuildTree = (arr) => {
        if (arr.length == 0)
            return null;
        let maxValue = -1;
        let maxIndex = -1;
        for (let i = 0; i <= arr.length-1; ++i) {
            if (arr[i] > maxValue) {
                maxValue = arr[i];
                maxIndex = i;
            }
        }
        let root = new TreeNode(maxValue);
        root.left = BuildTree(arr.slice(0,maxIndex));
        root.right = BuildTree(arr.slice(maxIndex+1));
        return root;
    }
    let root = BuildTree(nums);
    return root;
};

关键

  1. 找最大值的索引
  2. 处理边界,即遍历到的数组为空时写法
    if (arr.length == 0) return null;
    

617. 合并二叉树 - 力扣(LeetCode)

image.png

层序遍历

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

    let queue = [];
    queue.push(root1);
    queue.push(root2);
    while (queue.length) {
        let node1 = queue.shift();
        let node2 = queue.shift();;
        node1.val += node2.val;
        if (node1.left !== null && node2.left !== null) {
            queue.push(node1.left);
            queue.push(node2.left);
        }
        if (node1.right !== null && node2.right !== null) {
            queue.push(node1.right);
            queue.push(node2.right);
        }
        if (node1.left === null && node2.left !== null) {
            node1.left = node2.left;
        }
        if (node1.right === null && node2.right !== null) {
            node1.right = node2.right;
        } 
    }
    return root1;
};

关键

  1. 同时遍历两棵树
  2. 用队列出队的结点进行操作
  3. 判断终止条件

700. 二叉搜索树中的搜索 - 力扣(LeetCode)

image.png

递归

var searchBST = function (root, val) {

    if(!root) return root;
    
    const dfs = (root) => {
        if(!root) return root;
        if(root.val > val){
            return dfs(root.left)
        }
        if(root.val == val){
            return root;
        }
        if(root.val < val){
            return dfs(root.right)
        }
    }
    return dfs(root)
};

关键

  • 什么情况下才是返回一整个大结点?
  • 返回值要进行传递

98. 验证二叉搜索树 - 力扣(LeetCode)

image.png

var isValidBST = function(root) {
    let res = [];
    if(!root) return false;
    const dfs = (root) => {
        if(!root) return ;
        dfs(root.left)
        // console.log(root.val)
        res.push(root.val)
        dfs(root.right)
    }
    dfs(root)

    for(let i = 0; i < res.length;i++ ){
        if(res[i] >= res[i+1])
            return false;
    }
    return true;
};

关键

这里就比较有意思了,用了二叉搜索树的特性,中序遍历后,就是一个升序数组,如果遍历之后不是一个升序数组则不是二叉搜索树。

小结

今天由于时间比较赶,效率不搞,这一块还需要多多消化,争取早日三刷。