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

LeetCode 112: Path Sum

·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-16

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

解題思路
#

往下走的時候把目標減掉目前的值(Tree 模板一)。到了葉子,剩下的目標剛好等於葉子的值就找到了。一定要到葉子才算,路過中間的節點時剛好湊到不算。

我的嘗試
#

一版寫成 root == targetSum,拿節點本身跟整數比,永遠不相等,例如 [5]、targetSum = 5 回傳 False。另外兩版是變數沒定義、型別錯誤。

正確解法
#

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right:
            return root.val == targetSum
        rest = targetSum - root.val
        return self.hasPathSum(root.left, rest) or self.hasPathSum(root.right, rest)

複雜度
#

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

要特別避免的錯誤
#

  • 比較的是 root.val,不是節點本身。
  • 只在葉子判斷。

面試口說整理
#

我往下遞迴時把目標減掉目前的值,到葉子時檢查剩下的是否等於葉子的值,左右任一邊成立就回傳 True。時間 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 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 110: Balanced Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 解題筆記:每一個節點的左右高度差都不能超過 1;後序回傳高度,不平衡時回傳 -1 一路傳上去
LeetCode 144: Binary Tree Preorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 144 解題筆記:迭代的前序遍歷,彈出就記錄,先推右小孩再推左小孩,左邊才會先處理