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

LeetCode 257: Binary Tree Paths

·1 分鐘· ·
LeetCode Easy String Backtracking 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-22

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

解題思路
#

DFS 時把路徑一起往下傳(Tree 模板一),到葉子時就是一條完整的路徑。節點的值是整數,接成字串前要先 str()。

我的嘗試
#

前三版都是 TypeError:把整數 node.val 直接跟字串 "->" 相加。

正確解法
#

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        def dfs(node, path):
            if not node:
                return
            path = path + [str(node.val)]
            if not node.left and not node.right:
                res.append("->".join(path))
            dfs(node.left, path)
            dfs(node.right, path)
        dfs(root, [])
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 整數不能直接跟字串相加,要先 str()。

面試口說整理
#

我用 DFS 帶著目前的路徑往下,到葉子時用 -> 把路徑接成字串加進答案。時間 O(n · h)。

相關文章

LeetCode 226: Invert Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 解題筆記:每個節點交換左右小孩;用同時指定,避免先改掉的那邊被拿來用
LeetCode 145: Binary Tree Postorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 解題筆記:迭代的後序遍歷,節點第一次彈出時標記後放回去,再依序推右、左小孩;第二次彈出才記錄
LeetCode 110: Balanced Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 解題筆記:每一個節點的左右高度差都不能超過 1;後序回傳高度,不平衡時回傳 -1 一路傳上去
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 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右