-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path559.java
More file actions
60 lines (54 loc) · 1.39 KB
/
559.java
File metadata and controls
60 lines (54 loc) · 1.39 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
import java.util.LinkedList;
// 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;
}
};
// Recursion,其实也是DFS,tims complexity:worst->O(n),best->O(log(N)),
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
if (root.children == null) {
return 1;
}
int maxDepth = 0;
for (int i = 0; i < root.children.size(); i++) {
int d = maxDepth(root.children.get(i));
maxDepth=Math.max(maxDepth, d);
}
return maxDepth+1;
}
}
// BFS time complexity: O(N), space complexity: O(n)
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
LinkedList<Node> list = new LinkedList<>();
int depth = 0;
list.add(root);
while (!list.isEmpty()) {
depth++;
int size = list.size();
for (int i = 0; i < size; i++) {
Node node = list.pollFirst();
if (node != null && node.children != null) {
list.addAll(node.children);
}
}
}
return depth;
}
}