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 problem asks to find the maximum depth of an N-ary tree. The maximum depth is the number of nodes along the longest path from the root node to the farthest leaf node. We can solve this using either Depth-First Search (DFS) or Breadth-First Search (BFS), but DFS (recursive approach) is generally simpler and more efficient for tree traversal problems.
The recursive DFS approach leverages the inherent tree structure. The maximum depth of a tree is 1 plus the maximum depth of its children. The base case is when the node is null
, indicating an empty subtree, in which case the depth is 0.
Algorithm:
null
, return 0 (depth of an empty tree is 0).maxDepth
to 0. This variable will track the maximum depth among all children.maxDepth
to find the maximum depth of its subtree.maxDepth
with the maximum depth found among the children.1 + maxDepth
. The 1
accounts for the current node itself."""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None: # Base case: empty subtree
return 0
max_depth = 0
for child in root.children: # Iterate through children
max_depth = max(max_depth, self.maxDepth(child)) # Recursive call and update max
return 1 + max_depth # Add 1 for the current node
Other Languages: The implementation logic remains the same across different languages. The key differences are in syntax and data structure definitions (e.g., Node class). Refer to the provided code examples in Java, C++, Go, and TypeScript for their respective implementations.
Time Complexity: O(N), where N is the number of nodes in the tree. This is because each node is visited exactly once during the recursive traversal.
Space Complexity: O(H), where H is the height (or depth) of the tree. This space is used for the call stack during the recursive calls. In the worst case (a skewed tree), H can be equal to N. In a balanced tree, H is log₂N. Therefore, the space complexity can range from O(log N) to O(N) depending on the tree's structure.
While the recursive DFS approach is elegant, a BFS (iterative approach using a queue) is also possible. BFS would involve level-order traversal, keeping track of the current level. The maximum level reached would be the maximum depth. However, the recursive DFS approach is generally preferred for its simplicity and readability in this problem.