-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathMaximumDepthOfNaryTree.java
More file actions
91 lines (75 loc) · 2 KB
/
MaximumDepthOfNaryTree.java
File metadata and controls
91 lines (75 loc) · 2 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* LeetCode 559 https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
*/
/*
// 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 {
/**
* Recursion
*/
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int depth = 0;
for (Node child : root.children) {
depth = Math.max(maxDepth(child), depth);
}
return depth + 1;
}
/**
* Traverse
*/
int depth = 0;
int res = 0;
public int maxDepth(Node root) {
traverse(root);
return res;
}
public void traverse(Node node) {
if (node == null) {
return;
}
depth++;
res = Math.max(depth, res);
for (Node child : node.children) {
traverse(child);
}
depth--;
}
/**
* BFS with Queue
*/
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
Queue<Node> q = new LinkedList<>();
q.offer(root);
int depth = 0;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
Node cur = q.poll();
for (Node child : cur.children) {
q.offer(child);
}
}
depth++;
}
return depth;
}
}