DSA 部分中等

AVL樹

“AVL 樹”問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 is_avl_balanced(tree_arr) ,它採用二元樹 tree_arr 的陣列表示形式,如果樹是高度平衡的(對於每個節點,其左右子樹的高度最多相差 1)並且是有效的 BST,則傳回 True ,否則傳回 False

約束條件
  • 0 <= len(tree_arr) <= 1000

範例

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

The tree is a valid BST and the depth difference of left/right subtrees of all nodes is at most 1.

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

The tree is unbalanced because leaf node 4 is at depth 4 while right subtree of node 1 is empty.

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

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