150强访谈中等

平衡二叉树

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

问题陈述

中等

给定一棵二叉树,确定它是否是高度平衡的。

高度平衡二叉树是每个节点的两个子树的深度相差不超过一的二叉树。

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

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

示例

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

The left subtree (rooted at 9) has depth 1, and the right subtree (rooted at 20) has depth 2. The difference is 1, so the tree is balanced.

Example 2
Input
[1,2,2,3,3,None,None,4,4]
Output
False
Explanation

The left subtree has depth 3 while the right subtree has depth 1. The difference is 2, so the tree is not balanced.

Example 3
Input
[]
Output
True
Explanation

An empty tree is considered balanced.

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

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