559. Maximum Depth of N-ary Tree

LeetCode

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
private int maxDepthUtil(Node root,int depth){
if(root==null) return 0;
int maxDepth=depth;
for(Node node:root.children){
maxDepth=Math.max(maxDepth,maxDepthUtil(node,depth+1));
}
return maxDepth;
}
public int maxDepth(Node root) {
return maxDepthUtil(root,1);
}
}

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

public Node(int _val) {
val = _val;
}

public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
int depth=0;
if(root==null) return depth;
Queue<Node> q=new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int qSize=q.size();
while(qSize>0){
Node tmp=q.poll();
for(Node node:tmp.children){
if(q!=null){
q.offer(node);
}
}
qSize--;
}
depth++;
}
return depth;
}
}

0%