LeetCode 题解工作台
N 叉树的最大深度
给定一个 N 叉树,找到其最大深度。 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。 示例 1: 输入: root = [1,null,3,2,4,null,5,6] 输出: 3 示例 2: 输入: root = […
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们首先判断 是否为空,若为空则返回 0。否则我们初始化一个变量 用来记录子节点的最大深度,然后遍历 的所有子节点,递归调用 函数,更新 的值。最后返回 $\textit{mx} + 1$ 即可。 时间复杂度 ,空间复杂度 。其中 为节点的数量。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个 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]之间。
解题思路
方法一:递归
我们首先判断 是否为空,若为空则返回 0。否则我们初始化一个变量 用来记录子节点的最大深度,然后遍历 的所有子节点,递归调用 函数,更新 的值。最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为节点的数量。
"""
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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).
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.