[leetcode] problem 559 – maximum depth of n-ary tree

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

eXh8Ag.png

We should return its max depth, which is 3.

Note

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Code

1
2
3
4
5
6
7
8
public class  {
public int val;
public List<Node> children;
public (int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
1
2
3
4
5
6
7
8
9
10
11
public int maxDepth(Node root) {
if (root == null)
return 0;

int max = 0;

for (Node child : root.children)
max = Math.max(max, maxDepth(child));

return max + 1;
}