LeetCode 题解工作台

N 叉树的最大深度

给定一个 N 叉树,找到其最大深度。 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。 示例 1: 输入: root = [1,null,3,2,4,null,5,6] 输出: 3 示例 2: 输入: root = […

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

我们首先判断 是否为空,若为空则返回 0。否则我们初始化一个变量 用来记录子节点的最大深度,然后遍历 的所有子节点,递归调用 函数,更新 的值。最后返回 $\textit{mx} + 1$ 即可。 时间复杂度 ,空间复杂度 。其中 为节点的数量。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

 

示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:3

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5

 

提示:

  • 树的深度不会超过 1000
  • 树的节点数目位于 [0, 104] 之间。
lightbulb

解题思路

方法一:递归

我们首先判断 root\textit{root} 是否为空,若为空则返回 0。否则我们初始化一个变量 mx\textit{mx} 用来记录子节点的最大深度,然后遍历 root\textit{root} 的所有子节点,递归调用 maxDepth\text{maxDepth} 函数,更新 mx\textit{mx} 的值。最后返回 mx+1\textit{mx} + 1 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为节点的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""


class Solution:
    def maxDepth(self, root: "Node") -> int:
        if root is None:
            return 0
        mx = 0
        for child in root.children:
            mx = max(mx, self.maxDepth(child))
        return 1 + mx
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate efficiently navigates the tree and tracks depth correctly.

  • question_mark

    The solution includes the edge cases such as an empty tree or a single-node tree.

  • question_mark

    The candidate chooses an appropriate traversal technique based on tree structure (DFS vs. BFS).

warning

常见陷阱

外企场景
  • error

    Failing to handle edge cases like an empty tree (root = null) or single-node trees.

  • error

    Not accounting for trees with varying numbers of children, leading to inaccurate depth calculations.

  • error

    Incorrectly tracking depth or failing to update the maximum depth at each node.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implement the solution with a recursive approach using DFS.

  • arrow_right_alt

    Use an iterative BFS approach to solve for the maximum depth.

  • arrow_right_alt

    Optimize the solution to handle trees with large depths or wide breadth efficiently.

help

常见问题

外企场景

N 叉树的最大深度题解:二分·树·traversal | LeetCode #559 简单