代码随想录算法训练营第第16天 | 104.二叉树的最大深度 、111.二叉树的最小深度、222.完全二叉树的节点个数

104.二叉树的最大深度 (优先掌握递归)

什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。
大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.二叉树的最大深度.html

function depth(node) {
    if(node == null) return 0;
    let maxD = Math.max(depth(node.left)+1,depth(node.right)+1);
    return maxD
}
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    let max = depth(root);
    return max;
};

111.二叉树的最小深度 (优先掌握递归)

先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.二叉树的最小深度.html


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    if (root == null) return 0;
    if (root.left === null && root.right === null) return 1;
    let min = Infinity;
    if (root.left) {
        min = Math.min(minDepth(root.left)+1, min);
    }
    if (root.right) {
        min = Math.min(minDepth(root.right)+1, min);
    }
    return min;
};

222.完全二叉树的节点个数(优先掌握递归)

需要了解,普通二叉树 怎么求,完全二叉树又怎么求
题目链接/文章讲解/视频讲解:https://programmercarl.com/0222.完全二叉树的节点个数.html

利用完整二叉树的特性后续再补上,今天先学习其思想
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var countNodes = function(root) {
    if (root == null) return 0;
    let total = 1;
    if (root.left) {
        total += countNodes(root.left);
    }
    if (root.right) {
        total += countNodes(root.right);
    }
    return total;
};
posted @ 2024-05-24 00:01  YuanYF6  阅读(1)  评论(0编辑  收藏  举报