#559
Maximum Depth of N-ary Tree
EasyTreeDepth-First SearchBreadth-First SearchDepth-First SearchRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses Depth-First Search (DFS) to traverse the tree in a single pass, calculating the depth as we go. This is efficient because we only visit each node once.
⚙️
Algorithm
4 steps- 1Step 1: If the root is null, return 0.
- 2Step 2: Initialize a variable to keep track of the maximum depth.
- 3Step 3: For each child of the root, recursively calculate the depth and update the maximum depth.
- 4Step 4: Return the maximum depth found plus one for the current node.
solution.py10 lines
1class Node:
2 def __init__(self, val=None, children=None):
3 self.val = val
4 self.children = children if children is not None else []
5
6class Solution:
7 def maxDepth(self, root: Node) -> int:
8 if not root:
9 return 0
10 return 1 + max((self.maxDepth(child) for child in root.children), default=0)ℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursion stack in the worst case (for a completely unbalanced tree).
- 1Understanding tree traversal is crucial for depth calculations.
- 2Recursion can simplify the implementation of depth calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.