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

LeetCode 101: Symmetric 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-02

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

解題思路
#

對稱代表左子樹是右子樹的鏡像。寫一個比較兩棵樹是否鏡像的函式(Tree 模板一):值一樣,而且 a.left 對 b.right(外側)、a.right 對 b.left(內側)也都是鏡像。

我的嘗試
#

前兩版語法錯誤;之後有一版寫成 left == right,比的是節點物件而不是值,兩個不同的節點永遠不相等。例如 [3, 3, 3]:答案 True,回傳 False。

正確解法
#

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def mirror(a, b):
            if not a or not b:
                return a is b
            return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
        return mirror(root.left, root.right)

複雜度
#

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

要特別避免的錯誤
#

  • 比較的是 a.val == b.val;a == b 比的是兩個節點是不是同一個物件。

面試口說整理
#

我寫一個判斷兩棵樹是否互為鏡像的函式:值相同,外側和外側、內側和內側也互為鏡像,然後拿根的左右子樹去比。時間 O(n)。

相關文章

LeetCode 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右
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 解題筆記:迭代的前序遍歷,彈出就記錄,先推右小孩再推左小孩,左邊才會先處理
LeetCode 94: Binary Tree Inorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 94 解題筆記:迭代的中序遍歷,一路往左把節點推進 stack,彈出時記錄,再轉向右子樹
LeetCode 83: Remove Duplicates from Sorted List
·1 分鐘
LeetCode Easy Linked-List
LeetCode 83 解題筆記:已排序,重複的一定相鄰;cur 跟 cur.next 一樣就跳過 cur.next,不一樣才前進
LeetCode 69: Sqrt(x)
·1 分鐘
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 解題筆記:找最大的 mid 讓 mid² <= x;閉區間二分結束時 r 就是答案