leetcode 二叉树的最大深度与最小深度

122 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情

前言

继续刷二叉树模块专题,忍不住诉苦,二叉树的题真的多呀,不过解法也就那么几种,都是一些变形。

二叉树的最大深度

题目介绍

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

思路

这道题很容易想到层序遍历,我第一时间想到的就是它。不过是在遍历的每一层将全局变量height加一。这时候二叉树层序遍历的代码基本不用怎么改。

var maxDepth = function(root) {
    if(!root) return 0
    let height = 0
    const queue = [root]
    while(queue.length) {
        let size = queue.length
        /* height+1 */
        height++
        while(size--) {
            let node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
    }
    return height
};

不过解题后看到题解,发现递归遍历的方法也很简单,并且逻辑性更强。单层逻辑十分好理解:如果根节点没有,就返回0,二叉树的最大深度就是0;如果有root那么就分别递归其子树,取左右子树的最大深度。

var maxdepth = function(root) {
    const getdepth=function(node){
        if(node===null){
            return 0;
        }
        let leftdepth=getdepth(node.left);
        let rightdepth=getdepth(node.right);
        let depth=1+Math.max(leftdepth,rightdepth);
        return depth;
    }
    return getdepth(root);
};

拓展

有一道题n叉树的最大深度,解题思路与二叉树的最大深度基本一致,不过是n叉树不像二叉树,它的孩子不止两个,可能有多个。这时候只需要遍历一下n叉树的孩子就可以。这个题目的解法与前面的类似,这里就只给出递归解法。

var maxDepth = function(root) {
    if(!root) return 0
    let depth = 0
    for(let node of root.children) {
        depth = Math.max(depth, maxDepth(node))
    }
    return depth + 1
}

二叉树的最小深度

刚开始我以为这道题也过是第一道题的变法,但是尝试后总是出错。这时候注意到题目中关于最小深度的解释:

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

这样的话如果比如根节点没有右子树,那么最小深度不是1,因为不是根节点到最近叶子节点。这时候就需要进行判断了:

  1. 如果没有根节点,高度为0
  2. 如果有根节点但是没有左右子树,高度为1
  3. 如果只有左节点或者右节点,那么就需要递归另一边
  4. 如果两边都有,那么取小的

代码实现

var minDepth1 = function(root) {
    if(!root) return 0;
    if(!root.left && !root.right) return 1;
    if(!root.left) return 1 + minDepth(root.right);、
    if(!root.right) return 1 + minDepth(root.left);
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
};

后记

这几道题并不难,但是思想值得学习,而且要好好审题啊!