Skip to content

Commit fb801aa

Browse files
refactor 111
1 parent 458853e commit fb801aa

File tree

1 file changed

+43
-46
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+43
-46
lines changed

src/main/java/com/fishercoder/solutions/_111.java

Lines changed: 43 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -5,58 +5,55 @@
55
import java.util.LinkedList;
66
import java.util.Queue;
77

8-
/**
9-
* 111. Minimum Depth of Binary Tree
10-
*
11-
* Given a binary tree, find its minimum depth.
12-
* The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
13-
* */
14-
158
public class _111 {
169
public static class Solution1 {
17-
/**DFS*/
18-
public int minDepth(TreeNode root) {
19-
if (root == null) {
20-
return 0;
21-
}
22-
int left = minDepth(root.left);
23-
int right = minDepth(root.right);
24-
if (left == 0) {
25-
return right + 1;
26-
}
27-
if (right == 0) {
28-
return left + 1;
10+
/**
11+
* DFS
12+
*/
13+
public int minDepth(TreeNode root) {
14+
if (root == null) {
15+
return 0;
16+
}
17+
int left = minDepth(root.left);
18+
int right = minDepth(root.right);
19+
if (left == 0) {
20+
return right + 1;
21+
}
22+
if (right == 0) {
23+
return left + 1;
24+
}
25+
return Math.min(left, right) + 1;
2926
}
30-
return Math.min(left, right) + 1;
31-
}
3227
}
3328

34-
public static class Solution2 {
35-
/**BFS*/
36-
public int minDepth(TreeNode root) {
37-
if (root == null) {
38-
return 0;
39-
}
40-
Queue<TreeNode> q = new LinkedList();
41-
q.offer(root);
42-
int level = 0;
43-
while (!q.isEmpty()) {
44-
level++;
45-
int size = q.size();
46-
for (int i = 0; i < size; i++) {
47-
TreeNode curr = q.poll();
48-
if (curr.left != null) {
49-
q.offer(curr.left);
50-
}
51-
if (curr.right != null) {
52-
q.offer(curr.right);
53-
}
54-
if (curr.left == null && curr.right == null) {
29+
public static class Solution2 {
30+
/**
31+
* BFS
32+
*/
33+
public int minDepth(TreeNode root) {
34+
if (root == null) {
35+
return 0;
36+
}
37+
Queue<TreeNode> q = new LinkedList();
38+
q.offer(root);
39+
int level = 0;
40+
while (!q.isEmpty()) {
41+
level++;
42+
int size = q.size();
43+
for (int i = 0; i < size; i++) {
44+
TreeNode curr = q.poll();
45+
if (curr.left != null) {
46+
q.offer(curr.left);
47+
}
48+
if (curr.right != null) {
49+
q.offer(curr.right);
50+
}
51+
if (curr.left == null && curr.right == null) {
52+
return level;
53+
}
54+
}
55+
}
5556
return level;
56-
}
5757
}
58-
}
59-
return level;
6058
}
61-
}
6259
}

0 commit comments

Comments
 (0)