↓Skip to main content
  1. LeetCode/

LeetCode 559: Maximum Depth of N-ary Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Runtime Error ×3 → Wrong Answer → Runtime Error → Accepted → Runtime Error → Accepted

Approach
#

The same post-order return value as a binary tree (Tree Template 1), with children in a list: 1 + max(depth of each child). With no children, max on an empty sequence needs a default of 0.

My Attempts
#

The early versions mishandled empty trees or childless nodes: reading None.children or taking max of an empty list.

Solution
#

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)

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • An empty tree returns 0.
  • Give max a default when there are no children.

Interview Explanation
#

An n-ary tree’s depth is 1 plus its deepest child, computed recursively with a default of 0 for no children. Time O(n).

Related

LeetCode 404: Sum of Left Leaves
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 note: tell each child during DFS whether it is a left child, adding only left children that are leaves
LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum
LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf
LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides
LeetCode 101: Symmetric Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 note: the left and right subtrees must mirror each other, outer with outer and inner with inner; compare values, not node objects