Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

559. Maximum Depth of N-ary Tree - Leetcode Solution

Code Implementation

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        if not root.children:
            return 1
        return 1 + max(self.maxDepth(child) for child in root.children)
/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    int maxDepth(Node* root) {
        if (!root) return 0;
        if (root->children.empty()) return 1;
        int depth = 0;
        for (auto child : root->children) {
            depth = max(depth, maxDepth(child));
        }
        return depth + 1;
    }
};
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int val) {
        this.val = val;
    }

    public Node(int val, List<Node> children) {
        this.val = val;
        this.children = children;
    }
};
*/
class Solution {
    public int maxDepth(Node root) {
        if (root == null) return 0;
        if (root.children == null || root.children.size() == 0) return 1;
        int max = 0;
        for (Node child : root.children) {
            max = Math.max(max, maxDepth(child));
        }
        return max + 1;
    }
}
/**
 * // Definition for a Node.
 * function Node(val, children) {
 *    this.val = val;
 *    this.children = children || [];
 * };
 */
/**
 * @param {Node|null} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) return 0;
    if (!root.children || root.children.length === 0) return 1;
    let max = 0;
    for (let child of root.children) {
        max = Math.max(max, maxDepth(child));
    }
    return max + 1;
};

Problem Description

Given the root node root of an N-ary tree, your task is to determine the tree's maximum depth. The maximum depth is defined as the number of nodes along the longest path from the root node down to the farthest leaf node. Each node in the tree can have zero or more child nodes. If the tree is empty (i.e., root is null), return 0.

  • There is only one valid tree structure for each input.
  • Do not reuse nodes; each node is unique in the tree.

Thought Process

The problem asks for the maximum depth of an N-ary tree. At first glance, you might consider traversing every path from the root to each leaf and keeping track of the longest one. For a binary tree, this is often solved with recursion or a queue-based level-order traversal.

For an N-ary tree, the logic is similar, but each node can have any number of children. The naive approach would be to try all possible paths, but since each node is only part of one path from the root to a leaf, we don't need to consider combinations or permutations.

The key insight is that the depth at any node is 1 (the node itself) plus the greatest depth among its children. If a node has no children, its depth is 1. Recursion fits this pattern perfectly.

Solution Approach

We'll use a recursive Depth-First Search (DFS) approach to solve the problem. Here’s how:

  1. Base Case: If the root is null, we return 0 because an empty tree has depth 0.
  2. Leaf Node: If the node has no children, its maximum depth is 1.
  3. Recursive Step: For each child of the current node, recursively calculate its maximum depth.
  4. Combine Results: The maximum depth for the current node is 1 plus the maximum among all its children's depths.

This approach is efficient because each node is only visited once, and we never recompute the depth for any node.

Alternatively, you could use an iterative Breadth-First Search (BFS) with a queue, counting levels as you go, but the recursive approach is more direct and elegant for this problem.

Example Walkthrough

Example Input:

        1
      / | \
     2  3  4
        |   \
        5    6
  

Step-by-step:

  • Start at node 1. Children: 2, 3, 4.
  • Node 2 has no children. Depth = 1.
  • Node 3 has child 5. Node 5 has no children. Depth = 1 (for 5), so depth at 3 = 1 + 1 = 2.
  • Node 4 has child 6. Node 6 has no children. Depth = 1 (for 6), so depth at 4 = 1 + 1 = 2.
  • So, from node 1, the depths of children are [1, 2, 2]. The maximum is 2.
  • Add 1 for the root: 2 + 1 = 3.

The maximum depth of this tree is 3.

Time and Space Complexity

  • Brute-force: There is no real brute-force approach here since every node must be visited at least once to determine the depth. Any method will have to traverse all nodes.
  • Optimized (Recursive DFS):
    • Time Complexity: O(N), where N is the number of nodes in the tree. Each node is visited exactly once.
    • Space Complexity: O(H), where H is the height of the tree (due to the recursion stack). In the worst case (a skewed tree), H could be N.

Summary

To find the maximum depth of an N-ary tree, we use a simple recursive algorithm: for each node, the depth is 1 plus the maximum depth of its children. This approach is efficient, elegant, and leverages the natural recursive structure of trees. The solution visits each node once, making it optimal in both time and space for this problem.