给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
思路:利用for循环,分别求N叉树每个子树的深度,将子树的最大深度加一后并返回,即是树的最大深度。
//前序遍历求N叉树最大深度
public static int maxDepth(Node root) {
return preorder(root);
}
public static int preorder(Node root){
int depth=0;
if(root==null) return 0;
if(root.children==null) return 1;
//分别计算每个子树的最大深度
for(int i=0;i<root.children.size();i++){
depth=Math.max(preorder(root.children.get(i)),depth);
}
return depth+1;
}