Maximum Depth of N-ary Tree

easy tree dfs bfs

Problem

Given an n-ary tree, return its maximum depth: the number of nodes along the longest path from the root down to the farthest leaf.

Inputroot = [1, [3, [5, 6], 2, 4]]
Output3
Depth(root) = 1 + max(depth of each child).

def max_depth(root):
    if not root: return 0
    if not root.children: return 1
    return 1 + max(max_depth(c) for c in root.children)
function maxDepth(root) {
  if (!root) return 0;
  if (!root.children || !root.children.length) return 1;
  return 1 + Math.max(...root.children.map(maxDepth));
}
class Solution {
    public int maxDepth(Node root) {
        if (root == null) return 0;
        int best = 0;
        for (Node c : root.children) best = Math.max(best, maxDepth(c));
        return 1 + best;
    }
}
int maxDepth(Node* root) {
    if (!root) return 0;
    int best = 0;
    for (auto c : root->children) best = max(best, maxDepth(c));
    return 1 + best;
}
Time: O(n) Space: O(h) recursion