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

LeetCode 559: Maximum Depth of N-ary Tree

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

基本資料
#

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

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

解題思路
#

跟二元樹一樣是後序回傳值(Tree 模板一),只是小孩變成一個 list:1 + max(每個小孩的深度)。沒有小孩時 max 對空的序列要給預設值 0。

我的嘗試
#

前幾版都是空樹或沒有小孩的節點沒處理好:取 None.children、或對空的 list 取 max。

正確解法
#

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        return 1 + max((self.maxDepth(c) for c in root.children), default=0)

複雜度
#

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

要特別避免的錯誤
#

  • 空樹回傳 0。
  • 沒有小孩時 max 要有 default。

面試口說整理
#

N 叉樹的深度是 1 加上所有小孩深度的最大值,我用遞迴計算,沒有小孩時預設是 0。時間 O(n)。

相關文章

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(或等於葉子的值)就成立
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 解題筆記:左子樹跟右子樹互為鏡像:外側跟外側比、內側跟內側比;比的是值,不是節點本身