代码随想录算法训练营第十五天 | 二叉树

29 阅读1分钟

LeetCode 110. 平衡二叉树

📖 考察点

📖 题意理解

💡 解题思路

思路一:

思路二:

🔑 关键点总结

💻 代码实现

JavaScript

var isBalanced = function (root) {
    if (!root) {
        return true;
    }
    return recursionIsBalanced(root, 0)[0];
};

function recursionIsBalanced(root, curDepth) {
    if (root === null) {
        return [true, curDepth];
    }
    const [leftIsBalanced, leftDepth] = recursionIsBalanced(root.left, curDepth + 1);
    const [rigthIsBalanced, rightDepth] = recursionIsBalanced(root.right, curDepth + 1);
    const offsetDepth = Math.abs(leftDepth - rightDepth);
    if (leftIsBalanced && rigthIsBalanced && offsetDepth <= 1) {
        return [true, Math.max(leftDepth, rightDepth)];
    }
    return [false, -1];
}

⏱️ 复杂度分析

📚 总结与反思


LeetCode 257. 二叉树的所有路径

📖 考察点

二叉树的便历,回溯

📖 题意理解

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点

💡 解题思路

思路一:

思路二:

🔑 关键点总结

💻 代码实现

JavaScript

var binaryTreePaths = function(root) {
    const temp = [];
    const res = [];
    function backtrack(root){
        if(root === null){
            return;
        }
        temp.push(root.val);
        if(root.left === null && root.right === null){
            res.push(temp.join("->"));
            temp.pop();
            return;
        }
        backtrack(root.left);
        backtrack(root.right);
        temp.pop();
    }
    backtrack(root);
    return res;
};

⏱️ 复杂度分析

📚 总结与反思


LeetCode 404. 左叶子的和

📖 考察点

📖 题意理解

💡 解题思路

思路一:

思路二:

🔑 关键点总结

💻 代码实现

JavaScript

var sumOfLeftLeaves = function(root) {
    let queue = [];
    let res = 0;
    if(!root){
        return res;
    }
    queue.push(root);
    while(queue.length){
        let n = queue.length;
        for(let i =0;i<n;i++){
          let cur =  queue.pop();
          if(cur.left && !cur.left.left && !cur.left.right){
            res+=cur.left.val;
          }
          cur.left && queue.push(cur.left);
          cur.right && queue.push(cur.right);
        }
    }
    return res;
};

⏱️ 复杂度分析

📚 总结与反思


LeetCode 222. 完全二叉树节点的个数

📖 考察点

二叉树的便历

📖 题意理解

💡 解题思路

思路一:

思路二:

🔑 关键点总结

💻 代码实现

JavaScript

var countNodes = function(root) {
    //利用完全二叉树的特点
    if(root === null) {
        return 0;
    }
    let left = root.left;
    let right = root.right;
    let leftDepth = 0, rightDepth = 0;
    while(left) {
        left = left.left;
        leftDepth++;
    }
    while(right) {
        right = right.right;
        rightDepth++;
    }
    if(leftDepth == rightDepth) {
        return Math.pow(2, leftDepth+1) - 1;
    }
    return countNodes(root.left) + countNodes(root.right) + 1;
};

⏱️ 复杂度分析

📚 总结与反思