easy Maximum Depth of N-ary Tree
Problem Statement
Given a root of the n-ary tree, return the maximum depth of the tree.
The maximum depth refers to the longest path from the root node to any leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.
Examples
Example 1:
- Input: root =
[1,null,2,3,4,null,5]
- Expected Output:
3 - Justification: The path from the root node
1to the farthest leaf node5goes through nodes1 -> 2 -> 5, making the depth3.
Example 2:
- Input: root =
[1,null,2,3,4,null,5,null,6,7,8,null,9,10,null,11,12]
- Expected Output:
4 - Justification: The longest path from the root node
1to the farthest leaf node11or12is1 -> 2 -> 5 -> 12, resulting in a depth of4.
Example 3:
- Input: root =
[10,null,20,30,null,40,null,50,null,60]
- Expected Output:
4 - Justification: The path from the root node
10to the farthest leaf node60is10 -> 20 -> 40 -> 60, making the depth4.
Try it yourself
Try solving this question here:
✅ Solution Maximum Depth of N-ary Tree
Problem Statement
Given a root of the n-ary tree, return the maximum depth of the tree.
The maximum depth refers to the longest path from the root node to any leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.
Examples
Example 1:
- Input: root =
[1,null,2,3,4,null,5]
- Expected Output:
3 - Justification: The path from the root node
1to the farthest leaf node5goes through nodes1 -> 2 -> 5, making the depth3.
Example 2:
- Input: root =
[1,null,2,3,4,null,5,null,6,7,8,null,9,10,null,11,12]
- Expected Output:
4 - Justification: The longest path from the root node
1to the farthest leaf node11or12is1 -> 2 -> 5 -> 12, resulting in a depth of4.
Example 3:
- Input: root =
[10,null,20,30,null,40,null,50,null,60]
- Expected Output:
4 - Justification: The path from the root node
10to the farthest leaf node60is10 -> 20 -> 40 -> 60, making the depth4.
Solution
To solve this problem, we will use a Depth-First Search (DFS) approach. The idea is to explore each node starting from the root and go as deep as possible in each path before backtracking. For every node, we will recursively determine the depth of its children and keep track of the maximum depth encountered. Finally, we add one to account for the current node and return this value. This approach is effective because it ensures that all paths in the tree are explored, allowing us to accurately determine the maximum depth.
Step-by-Step Algorithm
-
Base case:
- If the root node is
null, return0since the tree is empty.
- If the root node is
-
Initialize Depth:
- Initialize a variable
maxDepthto0. This variable will store the maximum depth found so far.
- Initialize a variable
-
Iterate Over Children:
- If the root node has children, loop through each child node in the
root.childrenlist.
- If the root node has children, loop through each child node in the
-
Recursive Depth Calculation:
- For each child node, recursively call the
findmaxDepthmethod. - Capture the returned depth and update
maxDepthwith the maximum value between the currentmaxDepthand the returned depth.
- For each child node, recursively call the
-
Return Depth:
- After looping through all children, add
1to themaxDepthto account for the current node and return this value.
- After looping through all children, add
Algorithm Walkthrough
Input: root = [1, null, 2, 3, 4, null, 5]
-
Initialization:
maxDepthis initialized to0.
-
Iterate Over Children of Node 1:
- The method iterates over the children of
Node 1which areNode 2,Node 3, andNode 4.
- The method iterates over the children of
-
Recursive Call on Node 2:
- The method is called recursively with
root = Node 2. maxDepthis initialized to0forNode 2.
- The method is called recursively with
-
Iterate Over Children of Node 2:
- The method iterates over the children of
Node 2which isNode 5.
- The method iterates over the children of
-
Recursive Call on Node 5:
- The method is called recursively with
root = Node 5. - Since
Node 5has no children, the method returns1(maxDepth + 1).
- The method is called recursively with
-
Return Depth for Node 2:
- The method backtracks to
Node 2and updatesmaxDepthto1(the returned depth fromNode 5). - Adds
1tomaxDepthand returns2forNode 2.
- The method backtracks to
-
Recursive Call on Node 3:
- The method is called recursively with
root = Node 3. - Since
Node 3has no children, the method returns1(maxDepth + 1).
- The method is called recursively with
-
Recursive Call on Node 4:
- The method is called recursively with
root = Node 4. - Since
Node 4has no children, the method returns1(maxDepth + 1).
- The method is called recursively with
-
Return Depth for Root (Node 1):
- The method backtracks to
Node 1and updatesmaxDepthto2(maximum of the depths fromNode 2,Node 3, andNode 4). - Adds
1tomaxDepthand returns3forNode 1.
- The method backtracks to
-
Final Output:
- The final output is
3, representing the maximum depth of the tree.
- The final output is
Code
// class NAryNode {
// public int val;
// public List<NAryNode> children;
// // Constructor to initialize the NAryNode with a value
// public NAryNode(int val) {
// this.val = val;
// this.children = new ArrayList<>();
// }
// }
class Solution {
public int findmaxDepth(NAryNode root) {
if (root == null) {
return 0; // If the tree is empty, depth is 0
}
int maxDepth = 0; // Initialize the maximum depth to 0
// Iterate over all the children of the current NAryNode
for (NAryNode child : root.children) {
// Recursively find the depth of each child and update the maximum depth
maxDepth = Math.max(maxDepth, findmaxDepth(child));
}
return maxDepth + 1;
}
public static void main(String[] args) {
NAryNode root = new NAryNode(1);
NAryNode NAryNode2 = new NAryNode(2); // First child of root
NAryNode NAryNode3 = new NAryNode(3); // Second child of root
NAryNode NAryNode4 = new NAryNode(4); // Third child of root
NAryNode NAryNode5 = new NAryNode(5); // Child of NAryNode 3
// Construct the tree by adding children
root.children.add(NAryNode2);
root.children.add(NAryNode3);
root.children.add(NAryNode4);
NAryNode2.children.add(NAryNode5);
// Create a Solution object and test the maxDepth method
Solution solution = new Solution();
// Example 1
int result1 = solution.findmaxDepth(root);
System.out.println("Example 1 Output: " + result1); // Expected output: 3
}
}
Complexity Analysis
Time Complexity
The time complexity of the algorithm is N is the number of nodes in the tree. This is because the algorithm performs a Depth-First Search (DFS) on the tree, visiting each node exactly once.
Space Complexity
The space complexity of the algorithm is H is the height of the tree. This space is used by the call stack during the recursive depth-first traversal. In the worst case, the height of the tree could be equal to the number of nodes in the tree (e.g., in a skewed tree), making the space complexity
🤖 Don't fully get this? Learn it with Claude
Stuck on Maximum Depth of N-ary Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Maximum Depth of N-ary Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Maximum Depth of N-ary Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Maximum Depth of N-ary Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Maximum Depth of N-ary Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.