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 Tree INPUT N-ary Tree Structure 1 3 2 4 5 6 Depth 1 Depth 2 Depth 3 [1,null,3,2,4,null,5,6] Serialized level order ALGORITHM STEPS (Optimized DFS) 1 Base Case Check If root is null, return 0 2 Initialize Max Depth maxChildDepth = 0 3 Recurse on Children For each child: DFS call Update max if deeper 4 Return Result Return maxChildDepth + 1 DFS Traversal Order 1 --> 3 --> 5 (depth=3) 1 --> 3 --> 6 (depth=3) 1 --> 2 (depth=2) 1 --> 4 (depth=2) FINAL RESULT Longest Path Highlighted 1 3 2 4 5 6 Maximum Depth 3 OK - Verified Key Insight: DFS recursively finds the maximum depth among all children, then adds 1 for the current node. Time Complexity: O(n) - visits each node once. Space Complexity: O(h) - recursion stack where h = tree height. TutorialsPoint - Maximum Depth of N-ary Tree | Optimized DFS Approach
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