-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaximumDepthOfNaryTree.java
More file actions
72 lines (51 loc) · 1.53 KB
/
MaximumDepthOfNaryTree.java
File metadata and controls
72 lines (51 loc) · 1.53 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
/*
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.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
*/
public class MaximumDepthOfNaryTree {
public static int maxDepthBFS(Node root) {
int maxHeight = 0;
Deque<Node> q = new LinkedList<>();
if (root == null) return maxHeight;
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node cur = q.poll();
for (Node child : cur.children)
q.offer(child);
}
maxHeight++;
}
return maxHeight;
}
public int maxDepthDFS(Node root) {
if (root == null) return 0;
int max = 0;
for (Node child : root.children) {
int value = maxDepthDFS(child);
if (value > max)
max = value;
}
return max + 1;
}
// 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;
}
}
;
}