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

LeetCode 606: Construct String from Binary Tree

·1 分鐘· ·
LeetCode Medium String Tree Depth-First-Search Binary-Tree
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-08-28

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

解題思路
#

前序:先寫自己的值,再寫左右子樹(Tree 模板一)。括號的規則:

  • 葉子:只有值。
  • 右子樹是空的:右邊的括號可以省略。
  • 左子樹是空的、右子樹不是:左邊要留一個 (),不然分不出那是右小孩。

我的嘗試
#

第一版回傳的是一個 list,而且根也被包了括號,例如 [1] 回傳 ['(', '1', ')'],答案是 "1"。

正確解法
#

class Solution:
    def tree2str(self, root: Optional[TreeNode]) -> str:
        if not root:
            return ""
        s = str(root.val)
        if root.left or root.right:
            s += f"({self.tree2str(root.left)})"
        if root.right:
            s += f"({self.tree2str(root.right)})"
        return s

複雜度
#

時間 O(n²)(字串串接),用 list 收集再 join 可以到 O(n)。

要特別避免的錯誤
#

  • 只有左子樹空時才需要 ()。
  • 根本身不加括號。

面試口說整理
#

我用前序遞迴輸出:先寫值,有任何小孩就寫左子樹的括號(左邊是空的也要寫 ()),有右小孩才寫右子樹的括號。時間 O(n) 到 O(n²)。

相關文章

LeetCode 235: Lowest Common Ancestor of a Binary Search Tree
·1 分鐘
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 235 解題筆記:p、q 都比節點小就往左,都比節點大就往右,否則(一邊一個或其中一個就是自己)這個節點就是 LCA
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 501: Find Mode in Binary Search Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 解題筆記:BST 中序是排序的,相同的值會連在一起;中序時數目前這段的長度,比最大值大就重設答案,一樣大就加入
LeetCode 543: Diameter of Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 543 解題筆記:直徑可能不經過根;後序回傳高度,同時在每個節點用「左高 + 右高」更新答案;算的是邊數
LeetCode 404: Sum of Left Leaves
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 解題筆記:DFS 時告訴小孩自己是不是左小孩,只有「是左小孩而且是葉子」才加