/*
// 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;
if(root.children==null || root.children.size()==0)
return 1;
int depth = 0;
for (Node node : root.children) {
depth = Math.max(maxDepth(node),depth);
}
depth++;
return depth;
}
}
BFS
/*
// 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;
Queue<Node> queue = new LinkedList();
queue.offer(root);
int depth = 0;
while(!queue.isEmpty()) {
depth ++;
int count = queue.size();
for(int i=0; i<count; i++) {
Node node = queue.poll();
if(node!=null && node.children!=null) {
for(Node child : node.children) {
queue.offer(child);
}
}
}
}
return depth;
}
}