Maximum Depth of N-ary Tree - Problem
Imagine you're exploring a complex family tree where each person can have any number of children (not just two). Your mission is to find the deepest generation in this family lineage.
Given an N-ary tree (where each node can have 0 to N children), determine its maximum depth. The maximum depth represents the number of nodes along the longest path from the root node down to the farthest leaf node.
Key Points:
- The root node is at depth 1 (not 0)
- Each level down adds 1 to the depth
- A leaf node has no children
- We need to find the path with the most nodes from root to any leaf
Input: Root of an N-ary tree
Output: Integer representing the maximum depth
Input & Output
example_1.py — Basic N-ary Tree
$
Input:
root = [1,null,3,2,4,null,5,6]
›
Output:
3
💡 Note:
The tree has root 1 with children [3,2,4]. Node 3 has children [5,6]. The longest path is 1→3→5 (or 1→3→6), giving us a depth of 3 nodes.
example_2.py — Complex N-ary Tree
$
Input:
root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
›
Output:
5
💡 Note:
This tree has multiple levels. The deepest path goes through 5 levels: root→child→grandchild→great-grandchild→great-great-grandchild, resulting in a maximum depth of 5.
example_3.py — Single Node Tree
$
Input:
root = [1]
›
Output:
1
💡 Note:
A tree with only the root node has a depth of 1, since the root itself counts as one level.
Constraints
- The total number of nodes is in the range [0, 104]
- The depth of the n-ary tree will not exceed 1000
- Node values are unique
Visualization
Tap to expand
Understanding the Visualization
1
Start at Root
Begin at the root node (entrance of building) with depth 1
2
Explore All Children
For each child node, recursively find its maximum depth
3
Combine Results
Take the maximum depth among all children and add 1 for current level
4
Return Maximum
The recursion naturally returns the overall maximum depth
Key Takeaway
🎯 Key Insight: The maximum depth of an N-ary tree is found by recursively computing the maximum depth of all subtrees and adding 1. This elegant recursive solution mirrors the tree's natural structure and achieves optimal O(n) time complexity.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code