导航菜单

二叉树的最大深度

🟢 简单

题目描述

给定一个二叉树 root,返回其最大深度。二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1

输入:root = [3, 9, 20, null, null, 15, 7]
输出:3

示例 2

输入:root = [1, null, 2]
输出:2

提示

  • 树中节点的数量在 [0, 10^4] 区间内
  • -100 <= Node.val <= 100

解法一

参考答案 (3 个标签)
递归 DFS O(n)

思路

树的深度 = max(左子树深度, 右子树深度) + 1

代码实现

/**
 * 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}
 */
function maxDepth(root) {
    if (root === null) return 0;
    
    const leftDepth = maxDepth(root.left);
    const rightDepth = maxDepth(root.right);
    
    return Math.max(leftDepth, rightDepth) + 1;
}

复杂度分析

  • 时间复杂度:O(n),每个节点访问一次
  • 空间复杂度:O(h),h 为树的高度,最坏 O(n)

解法二

参考答案 (3 个标签)
BFS 迭代 O(n)

思路

使用队列进行层序遍历,记录层数。

代码实现

/**
 * @param {TreeNode} root
 * @return {number}
 */
function maxDepth(root) {
    if (root === null) return 0;
    
    const queue = [root];
    let depth = 0;
    
    while (queue.length > 0) {
        const size = queue.length;
        depth++;
        
        for (let i = 0; i < size; i++) {
            const node = queue.shift();
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
    }
    
    return depth;
}

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(w),w 为树的最大宽度

搜索