LeetCode 559: Maximum Depth of N-ary Tree

Problem Description

Explanation:

To find the maximum depth of an N-ary tree, we can use a recursive approach. We start from the root node and recursively calculate the maximum depth of each child node. The maximum depth of the tree is the maximum of the depths of all child nodes plus 1 (to account for the current level).

Algorithm:

  1. If the root node is null, return 0.
  2. Initialize a variable maxDepth to 1 (accounting for the current level).
  3. For each child node of the root node, recursively calculate the depth and update maxDepth with the maximum depth found.
  4. Return maxDepth.

Time Complexity:

The time complexity of this algorithm is O(N), where N is the total number of nodes in the N-ary tree.

Space Complexity:

The space complexity is O(H), where H is the height of the tree.

Solutions

class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        
        int maxDepth = 1;
        for (Node child : root.children) {
            maxDepth = Math.max(maxDepth, 1 + maxDepth(child));
        }
        
        return maxDepth;
    }
}

Loading editor...