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.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:

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

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
Constraints:
[0, 104].1000.This approach leverages the recursive nature of trees to calculate the depth. For each node, if it has no children, it is a leaf and has depth 1. Otherwise, recursively calculate the depth of each child and take the maximum depth found among all children, adding 1 for the current node to account for the path to parent.
The function maxDepth is implemented recursively. We check if the root is None and return 0 which indicates an empty tree. If the node has no children, return 1, indicating it is a leaf. For a node with children, recursively calculate the max depth for each child and add 1 to the result to represent the current node.
JavaScript
Java
C++
C
C#
The time complexity is O(n), where n is the number of nodes in the tree. Each node is visited once. The space complexity is O(h) where h is the height of the tree, representing the function call stack during the recursion.
This approach utilizes BFS using a queue to iteratively compute tree depth. Nodes are enqueued level by level. At each level, we count its nodes, dequeuing them and enqueueing their children, indicating traversing to the next tree level. We increment a level counter as we progress deeper into the tree.
We use a deque to facilitate breadth-first traversal. In each loop iteration, we process all nodes at the current level and enqueue their children. Each iteration over the level represents moving a depth deeper, and we count these iterations to find the final maximum depth.
JavaScript
Java
C++
C
C#
The time complexity is O(n) as we process each node once. The space complexity is O(n) for holding nodes of the widest level in the queue.
| Approach | Complexity |
|---|---|
| Recursive Depth-First Search (DFS) Approach | The time complexity is O(n), where n is the number of nodes in the tree. Each node is visited once. The space complexity is O(h) where h is the height of the tree, representing the function call stack during the recursion. |
| Iterative Breadth-First Search (BFS) Approach | The time complexity is O(n) as we process each node once. The space complexity is O(n) for holding nodes of the widest level in the queue. |
Maximum Depth of Binary Tree - 3 Solutions - Leetcode 104 - Python • NeetCode • 296,166 views views
Watch 9 more video solutions →Practice Maximum Depth of N-ary Tree with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor