↓快轉到主要內容
  1. LeetCode/

LeetCode 110: Balanced Binary Tree

·1 分鐘· ·
LeetCode Easy Tree Depth-First-Search Binary-Tree
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-16

  • 提交紀錄:Wrong Answer → Runtime Error ×2 → Wrong Answer → Runtime Error → Wrong Answer → Runtime Error ×2 → Accepted → Wrong Answer ×2 → Accepted ×2 → Runtime Error → Accepted → Time Limit Exceeded → Accepted ×2 → Wrong Answer → Runtime Error → Wrong Answer → Runtime Error ×2

解題思路
#

平衡要求每一個節點都平衡,不只是根(Tree 模板一)。後序回傳子樹的高度,一旦發現某個節點不平衡就回傳 -1,上面的節點看到 -1 直接往上傳,這樣只要走一次,O(n)。

我的嘗試
#

這題 2022 年提交了 18 次,2026 年重寫時又錯了 5 次:

  • 很多次是空樹沒處理(None.left),或用了沒定義的變數。
  • 有兩版只檢查根的左右高度差:abs(depth(root.left) - depth(root.right)) <= 1。例如 [5, 5, 1, 5, None, 5, 3, 4]:根兩邊高度差 1,但左子樹的根左邊有兩層、右邊是空的,答案 False,回傳 True。
  • 2026 年的幾版都還是在空樹時出錯。

正確解法
#

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def height(node):
            if not node:
                return 0
            l, r = height(node.left), height(node.right)
            if l < 0 or r < 0 or abs(l - r) > 1:
                return -1                            # 已經不平衡
            return 1 + max(l, r)
        return height(root) >= 0

複雜度
#

時間 O(n),空間 O(h)。

要特別避免的錯誤
#

  • 只檢查根的左右高度差不夠,下面的節點也要平衡。
  • 每個節點都重新算高度是 O(n²);用 -1 往上傳只要 O(n)。

面試口說整理
#

平衡要每個節點都平衡,所以我用後序回傳高度,發現不平衡就回傳 -1 一路往上傳,最後看根的結果是不是 -1。只走一次,時間 O(n)。

相關文章

LeetCode 111: Minimum Depth of Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 解題筆記:最小深度要到葉子才算;只有一邊有小孩時不能拿空的那邊(深度 0)當最小值
LeetCode 112: Path Sum
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 解題筆記:往下走時把 targetSum 減掉目前的值,到葉子時剛好是 0(或等於葉子的值)就成立
LeetCode 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右
LeetCode 101: Symmetric Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 解題筆記:左子樹跟右子樹互為鏡像:外側跟外側比、內側跟內側比;比的是值,不是節點本身
LeetCode 104: Maximum Depth of Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 104 解題筆記:深度等於 1 加上左右子樹深度的較大值;空樹是 0
LeetCode 144: Binary Tree Preorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 解題筆記:迭代的前序遍歷,彈出就記錄,先推右小孩再推左小孩,左邊才會先處理