-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode104.java
More file actions
60 lines (53 loc) · 1.53 KB
/
LeetCode104.java
File metadata and controls
60 lines (53 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
import java.util.Queue;
import java.util.LinkedList;
import util.TreeNode;
public class LeetCode104 {
public static void main(String[] args) {
// 输入:root = [3,9,20,null,null,15,7]
// 输出:3
System.out
.println(new Solution104_2()
.maxDepth(TreeNode.buildTree(new Integer[] { 3, 9, 20, null, null, 15, 7 })));
// 输入:root = [1,null,2]
// 输出:2
System.out
.println(new Solution104_2().maxDepth(TreeNode.buildTree(new Integer[] { 1, null, 2 })));
}
}
class Solution104_1 {
// BFS
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int ans = 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (queue.size() > 0) {
int n = queue.size();
for (int i = 0; i < n; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
ans++;
}
return ans;
}
}
class Solution104_2 {
// DFS
public int maxDepth(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode node, int depth) {
if (node == null) {
return depth;
}
return Math.max(dfs(node.left, depth), dfs(node.right, depth)) + 1;
}
}