150强访谈中等

二叉树的直径

“二叉树直径”问题的详细指南和 Python 实现。

问题陈述

中等

给定二叉树的根,返回树的直径长度。

二叉树的直径是树中任意两个节点之间最长路径的长度。该路径可能会也可能不会通过根。

两个节点之间的路径长度由它们之间的边数表示。

该树被表示为一个级别顺序列表。实现函数 diameterOfBinaryTree(root: list) -> int

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

示例

Example 1
Input
[1,2,3,4,5]
Output
3
Explanation

The longest path is 4->2->1->3 or 5->2->1->3, which has 3 edges.

Example 2
Input
[1,2]
Output
1
Explanation

The longest path is 2->1, which has 1 edge.

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 资源

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