Description:
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:

LeetCode-Maximum Depth of N-ary Tree_Java

We should return its max depth, which is 3.

Note:

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

题意:返回一颗N叉树的最大深度,即根节点到最远叶子节点的距离;

解法:我们可以利用递归来计算N叉树的最大深度;对于每一个节点,我们遍历其所有节点,那么这个节点的深度就是其子节点中的最大深度加1;对于子节点,递归调用求解子节点的深度;

Java
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int max = 1;
for (int i = 0; i < root.children.size(); i++) {
max = Math.max(max, maxDepth(root.children.get(i)) + 1);
}
return max;
}
}