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

LeetCode 653: Two Sum IV - Input is a BST

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

基本資料
#

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

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

解題思路
#

跟 Two Sum 一樣,用集合記住看過的值(Hash Table)。遍歷每個節點時,先看 k - val 有沒有出現過,有就回傳 True,再把自己加進去。用中序加雙指針也可以利用 BST 的排序性質,但集合最簡單。

我的嘗試
#

第一版變數沒定義。我 AC 的版本多了 if k == 0: return False,但 k 可以是 0、樹裡也可能同時有 -1 和 1,這個判斷其實是錯的,只是剛好沒被測到;11 月重寫時一版沒有回傳值。

正確解法
#

class Solution:
    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
        seen, stack = set(), [root]
        while stack:
            node = stack.pop()
            if not node:
                continue
            if k - node.val in seen:
                return True
            seen.add(node.val)
            stack += [node.left, node.right]
        return False

複雜度
#

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

要特別避免的錯誤
#

  • 要先查再加,不然同一個節點會跟自己配對。
  • k 可以是 0(例如 -1 和 1),不要把 k == 0 當成不可能。

面試口說整理
#

我遍歷整棵樹,用集合記看過的值,每到一個節點先檢查 k - val 是否已經看過,再把自己加進集合。時間和空間都是 O(n)。

相關文章

LeetCode 637: Average of Levels in Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 解題筆記:層序遍歷,每層加總除以節點數
LeetCode 671: Second Minimum Node In a Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 671 解題筆記:根就是最小值;第二小值是整棵樹裡第一個比根大的最小值,值等於根的子樹才需要往下找
LeetCode 559: Maximum Depth of N-ary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search
LeetCode 559 解題筆記:深度等於 1 加上所有小孩深度的最大值;沒有小孩時是 1
LeetCode 563: Binary Tree Tilt
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 563 解題筆記:後序回傳子樹的總和,每個節點的 tilt 是左右子樹總和的差,加進答案
LeetCode 572: Subtree of Another Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search String-Matching Binary-Tree
LeetCode 572 解題筆記:對 root 的每一個節點都檢查一次「以它為根的子樹跟 subRoot 是否相同」;遞迴時要呼叫 isSubtree,不是只比左右小孩
LeetCode 589: N-ary Tree Preorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search
LeetCode 589 解題筆記:N 叉樹的前序,先記錄自己,再依序處理每個小孩;遞迴結果要用 extend 攤平,不是 append 一個 list