「前端刷题」104. 二叉树的最大深度

329 阅读2分钟

「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战」。

题目

链接:leetcode-cn.com/problems/ma… 给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

3

/ \ 9 20 / \ 15 7

返回它的最大深度 3 。

思路

1.求最大深度,考虑使用深度优先遍历
2.在深度优先遍历过程中,记录每个节点所在的层级,找出最大层级即可

步骤

1.新建一个变量res,记录最大深度
2.深度优先遍历整棵树,并记录每个节点的层级,同时不断刷新最大深度这个变量
3.遍历结束返回最大深度这个变量

时空分析

时间复杂度:O(n), n为整棵树的节点数
空间复杂度:最好O(log n),最坏O(n), n为整棵树的节点数

代码

/**
 * 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 res = 0 // 最大深度
    // 求最大深度使用深度优先遍历;求最小深度使用广度优先遍历
    // l代表当前节点所在层级
    const dfs = (n, l) => {
        if(!n) return
        // 只在叶子节点时做判断
        if(!n.left && !n.right) {
            res = Math.max(res, l)
        }
        dfs(n.left, l+1)
        dfs(n.right, l+1)
    }
    dfs(root, 1)
    return res
};

思路2

一个节点的深度等于1加左节点和有节点深度的较大者,用公式表示 h(r)=Math.max(h(r.left), h(right)) + 1,所以可以深度遍历左右子树,返回左右子树的最大深度。 复杂度分析:时间复杂度O(n), 其中 n 为二叉树节点的个数。空间复杂度O(n), 其中n 表示二叉树的高度,最坏的情况下和树的节点数相同

var maxDepth = function(root) {
    if(!root) {
        return 0;
    } else {
        const left = maxDepth(root.left);//递归左子树
        const right = maxDepth(root.right);//递归右子树
        return Math.max(left, right) + 1;//1加左节点和有节点深度的较大者
    }
};

bfs

const maxDepth = (root) => {
    if (root == null) return 0;
    const queue = [root];
    let depth = 1;
    while (queue.length) {
        // 当前层的节点个数
        const levelSize = queue.length;          
        // 逐个让当前层的节点出列
        for (let i = 0; i < levelSize; i++) {    
            // 当前出列的节点
            const cur = queue.shift();            
            // 左右子节点入列
            if (cur.left) queue.push(cur.left);
            if (cur.right) queue.push(cur.right); 
        }
        // 当前层所有节点已经出列,如果队列不为空,说明有下一层节点,depth+1
        if (queue.length) depth++;
    }
    return depth;
};