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

LeetCode 993: Cousins in 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-09-26

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

解題思路
#

堂兄弟有兩個條件:深度相同、父節點不同(Tree 模板一)。DFS 時帶著父節點和深度,找到 x、y 時記下來,最後兩個條件都檢查。

我的嘗試
#

前幾版只比較深度,沒有檢查父節點。例如 [17, 3, 8]、x = 3、y = 8:兩個是兄弟,答案 False,回傳 True。

正確解法
#

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        info = {}
        def dfs(node, parent, depth):
            if not node:
                return
            if node.val in (x, y):
                info[node.val] = (parent, depth)
            dfs(node.left, node, depth + 1)
            dfs(node.right, node, depth + 1)
        dfs(root, None, 0)
        (px, dx), (py, dy) = info[x], info[y]
        return dx == dy and px is not py

複雜度
#

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

要特別避免的錯誤
#

  • 同一層的兄弟(同一個父節點)不是堂兄弟。

面試口說整理
#

堂兄弟要同一層而且父節點不同,所以我用 DFS 記下 x 和 y 的深度和父節點,最後兩個條件都檢查。時間 O(n)。

相關文章

LeetCode 965: Univalued Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 解題筆記:每個節點的值都要等於根的值;遞迴時比的是值,不是遞迴回傳的布林值
LeetCode 637: Average of Levels in Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 解題筆記:層序遍歷,每層加總除以節點數
LeetCode 404: Sum of Left Leaves
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 解題筆記:DFS 時告訴小孩自己是不是左小孩,只有「是左小孩而且是葉子」才加
LeetCode 226: Invert Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 解題筆記:每個節點交換左右小孩;用同時指定,避免先改掉的那邊被拿來用
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(或等於葉子的值)就成立