150强访谈

二叉树的最大深度

“二叉树最大深度”问题的详细指南和 Python 实现。

问题陈述

给定二叉树的根,返回其最大深度。

二叉树的最大深度是从根节点到最远叶节点的最长路径上的节点数。

该树表示为一个级别顺序列表,其中 None 表示缺失节点。实现函数 maxDepth(root: list) -> int

约束条件
  • The number of nodes in the tree is in the range [0, 10000]
  • -100 <= Node.val <= 100

示例

Example 1
Input
[3,9,20,None,None,15,7]
Output
3
Explanation

The tree has 3 levels: root [3], second level [9,20], third level [15,7]. The longest path is 3->20->15 or 3->20->7, both of depth 3.

Example 2
Input
[1,None,2]
Output
2
Explanation

The tree has root 1 with only a right child 2. Depth is 2.

Example 3
Input
[]
Output
0
Explanation

An empty tree has depth 0.

Need a Hint?
考虑使用树特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。