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

LeetCode 226: Invert Binary Tree

·1 分鐘· ·
LeetCode Easy Tree Depth-First-Search Breadth-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-21

  • 提交紀錄:Runtime Error ×4 → Accepted ×3 → Runtime Error → Accepted → Wrong Answer → Accepted ×2

解題思路
#

每個節點把左右子樹交換,再對兩邊遞迴(Tree 模板一)。用 root.left, root.right = 右, 左 同時指定:右邊兩個值會先算好,才不會發生「左邊改完之後,右邊拿到的是已經被改過的左邊」。

我的嘗試
#

前幾版回傳的不是樹(例如回傳了一個 list),或沒處理空樹。之後有一版分成兩行:

root.left = invert(root.right)
root.right = invert(root.left)   # 這裡的 root.left 已經是新的

第二行用到的是已經被改過的左子樹,原本的左子樹不見了。例如 [1, 4]:答案 [1, None, 4],回傳 [1]。

正確解法
#

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root:
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root

複雜度
#

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

要特別避免的錯誤
#

  • 分兩行寫時,第二行用到的 root.left 已經是新的值。

面試口說整理
#

我對每個節點交換左右子樹,再遞迴處理兩邊,用同時指定避免覆蓋。時間 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 145: Binary Tree Postorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 解題筆記:迭代的後序遍歷,節點第一次彈出時標記後放回去,再依序推右、左小孩;第二次彈出才記錄