public int maxDepth(Node root) {
if (root == null) {
return 0;
} else if (root.children.isEmpty()) {
return 1;
} else {
List<Integer> heights = new LinkedList<>();
for (Node item : root.children) {
heights.add(maxDepth(item));
}
return Collections.max(heights) + 1;
}
public int maxDepth(Node root) {
Queue<Node> que=new LinkedList();
int depth=0;
if(root!=null){
que.add(root);
}
while(!que.isEmpty()){
int size=que.size();
depth++;
for(int i=0;i<size;i++){
Node node=que.peek();
que.poll();
for(Node val:node.children){
if(val!=null){
que.add(val);
}
}
}
}
return depth;
}
public int maxDepth(Node root) {
Queue<Pair<Node, Integer>> stack = new LinkedList<>();
if (root != null) {
stack.add(new Pair(root, 1));
}
int depth = 0;
while (!stack.isEmpty()) {
Pair<Node, Integer> current = stack.poll();
root = current.getKey();
int current_depth = current.getValue();
if (root != null) {
depth = Math.max(depth, current_depth);
for (Node c : root.children) {
stack.add(new Pair(c, current_depth + 1));
}
}
}
return depth;
}
//作者:LeetCode
//链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/solution/ncha-shu-de-zui-da-shen-du-by-leetcode/
public int maxDepth(Node root) {
if (null == root) {
return 0;
}
int result = 1;
for (Node child : root.children) {
result = Math.max(result, 1 + maxDepth(child));
}
return result;
}