Maximum Depth of N-ary Tree — LeetCode 559 Python Solution

EasyTreeDepth-First SearchBreadth-First Search
Problem
#559
Reading time
3 min

The problem

Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example

Input
root = [1,null,3,2,4,null,5,6]
Output
3

Python solution

Python
"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""


class Solution:
    def maxDepth(self, root: "Node") -> int:
        if root is None:
            return 0
        mx = 0
        for child in root.children:
            mx = max(mx, self.maxDepth(child))
        return 1 + mx

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 559. Maximum Depth of N-ary Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 559. Maximum Depth of N-ary Tree?
LeetCode 559. Maximum Depth of N-ary Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 559. Maximum Depth of N-ary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 559. Maximum Depth of N-ary Tree?
The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.
What topics does LeetCode 559. Maximum Depth of N-ary Tree cover?
LeetCode 559. Maximum Depth of N-ary Tree is tagged Tree, Depth-First Search and Breadth-First Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview