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

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。