Knowledge Guide
HomeDSATrees

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:

Image
Image

Example 2:

Image
Image

Example 3:

Image
Image

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]
Image
Image
  • Expected Output: 3
  • Justification: The path from the root node 1 to the farthest leaf node 5 goes through nodes 1 -> 2 -> 5, making the depth 3.

Example 2:

  • Input: root = [1,null,2,3,4,null,5,null,6,7,8,null,9,10,null,11,12]
Image
Image
  • Expected Output: 4
  • Justification: The longest path from the root node 1 to the farthest leaf node 11 or 12 is 1 -> 2 -> 5 -> 12, resulting in a depth of 4.

Example 3:

  • Input: root = [10,null,20,30,null,40,null,50,null,60]
Image
Image
  • Expected Output: 4
  • Justification: The path from the root node 10 to the farthest leaf node 60 is 10 -> 20 -> 40 -> 60, making the depth 4.

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

  1. Base case:

    • If the root node is null, return 0 since the tree is empty.
  2. Initialize Depth:

    • Initialize a variable maxDepth to 0. This variable will store the maximum depth found so far.
  3. Iterate Over Children:

    • If the root node has children, loop through each child node in the root.children list.
  4. Recursive Depth Calculation:

    • For each child node, recursively call the findmaxDepth method.
    • Capture the returned depth and update maxDepth with the maximum value between the current maxDepth and the returned depth.
  5. Return Depth:

    • After looping through all children, add 1 to the maxDepth to account for the current node and return this value.

Algorithm Walkthrough

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

  1. Initialization:

    • maxDepth is initialized to 0.
  2. Iterate Over Children of Node 1:

    • The method iterates over the children of Node 1 which are Node 2, Node 3, and Node 4.
  3. Recursive Call on Node 2:

    • The method is called recursively with root = Node 2.
    • maxDepth is initialized to 0 for Node 2.
  4. Iterate Over Children of Node 2:

    • The method iterates over the children of Node 2 which is Node 5.
  5. Recursive Call on Node 5:

    • The method is called recursively with root = Node 5.
    • Since Node 5 has no children, the method returns 1 (maxDepth + 1).
  6. Return Depth for Node 2:

    • The method backtracks to Node 2 and updates maxDepth to 1 (the returned depth from Node 5).
    • Adds 1 to maxDepth and returns 2 for Node 2.
  7. Recursive Call on Node 3:

    • The method is called recursively with root = Node 3.
    • Since Node 3 has no children, the method returns 1 (maxDepth + 1).
  8. Recursive Call on Node 4:

    • The method is called recursively with root = Node 4.
    • Since Node 4 has no children, the method returns 1 (maxDepth + 1).
  9. Return Depth for Root (Node 1):

    • The method backtracks to Node 1 and updates maxDepth to 2 (maximum of the depths from Node 2, Node 3, and Node 4).
    • Adds 1 to maxDepth and returns 3 for Node 1.
  10. Final Output:

    • The final output is 3, representing the maximum depth of the tree.

Code

java
// 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 , where 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 , where 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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes