Maximum Depth of N-ary Tree - Problem

Given an 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.

Note: Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.

Input & Output

Example 1 — Standard N-ary Tree
$ Input: root = [1,null,3,2,4,null,5,6]
Output: 3
💡 Note: The tree has 3 levels: root (1) → children (3,2,4) → grandchildren (5,6). The maximum depth is 3.
Example 2 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Tree has only the root node, so maximum depth is 1.
Example 3 — Linear Tree
$ Input: root = [1,null,2,null,3,null,4]
Output: 4
💡 Note: Each node has one child forming a linear chain: 1→2→3→4, depth is 4.

Constraints

  • The total number of nodes is in the range [0, 104]
  • The depth of the n-ary tree is less than or equal to 1000

Visualization

Tap to expand
Maximum Depth of N-ary Tree1Root (Level 1)324Children (Level 2)56Leaves (Level 3)Possible Paths:• 1 → 3 → 5 (depth 3)• 1 → 3 → 6 (depth 3)• 1 → 2 (depth 2)• 1 → 4 (depth 2)Maximum Depth3
Understanding the Visualization
1
Input Tree
N-ary tree with nodes having multiple children
2
Find Paths
Identify all root-to-leaf paths
3
Count Max
Return length of longest path
Key Takeaway
🎯 Key Insight: Maximum depth is 1 + maximum depth among all child subtrees
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
85.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen