-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
103 lines (98 loc) · 2.59 KB
/
Solution.java
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
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.TreeSet;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
// Recursive
class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
// BFS
class Solution2 {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()){
int size = queue.size();
while (size-- > 0){
TreeNode node = queue.poll();
if (node.left != null){
queue.offer(node.left);
}
if (node.right != null){
queue.offer(node.right);
}
}
depth += 1;
}
return depth;
}
}
// DFS
class Solution3 {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> value = new Stack<>();
stack.push(root);
value.push(1);
int depth = 0;
while (!stack.isEmpty()){
TreeNode node = stack.pop();
int tmp = value.pop();
depth = Math.max(tmp, depth);
if(node.left != null){
stack.push(node.left);
value.push(tmp + 1);
}
if(node.right != null){
stack.push(node.right);
value.push(tmp + 1);
}
}
return depth;
}
}
// update after debug
class Solution4 {
public int maxDepth(TreeNode root) {
int depth = 0;
List<TreeNode> level = new ArrayList<>();
if (root != null){
level.add(root);
}
while (!level.isEmpty()){
depth += 1;
List<TreeNode> queue = new ArrayList<>();
for(int i = 0; i < level.size(); i++){
root = level.get(i); // iterator
if (root.left != null) {
queue.add(root.left);
}
if (root.right != null) {
queue.add(root.right);
}
}
level = queue;
}
return depth;
}
}