Skip to content

Commit 1abc4fb

Browse files
refactor 111
1 parent 66e640e commit 1abc4fb

File tree

1 file changed

+41
-47
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+41
-47
lines changed

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

Lines changed: 41 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -7,62 +7,56 @@
77

88
/**
99
* 111. Minimum Depth of Binary Tree
10+
*
1011
* Given a binary tree, find its minimum depth.
1112
* The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
1213
* */
1314

1415
public class _111 {
15-
/**
16-
* We can solve this problem using both BFS and DFS:
17-
* DFS is to visit every single root to leaf path and return the shortest one.
18-
* BFS is to visit every level and return whenever we find the first leaf node.
19-
*/
20-
21-
public static class DFSSolution {
22-
23-
public int minDepth(TreeNode root) {
24-
if (root == null) {
25-
return 0;
26-
}
27-
int left = minDepth(root.left);
28-
int right = minDepth(root.right);
29-
if (left == 0) {
30-
return right + 1;
31-
}
32-
if (right == 0) {
33-
return left + 1;
34-
}
35-
return Math.min(left, right) + 1;
16+
public static class Solution1 {
17+
/**DFS*/
18+
public int minDepth(TreeNode root) {
19+
if (root == null) {
20+
return 0;
3621
}
37-
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;
29+
}
30+
return Math.min(left, right) + 1;
31+
}
3832
}
3933

40-
public static class BFSSolution {
41-
42-
public int minDepth_BFS(TreeNode root) {
43-
if (root == null) {
44-
return 0;
45-
}
46-
Queue<TreeNode> q = new LinkedList();
47-
q.offer(root);
48-
int level = 0;
49-
while (!q.isEmpty()) {
50-
level++;
51-
int size = q.size();
52-
for (int i = 0; i < size; i++) {
53-
TreeNode curr = q.poll();
54-
if (curr.left != null) {
55-
q.offer(curr.left);
56-
}
57-
if (curr.right != null) {
58-
q.offer(curr.right);
59-
}
60-
if (curr.left == null && curr.right == null) {
61-
return level;
62-
}
63-
}
64-
}
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) {
6555
return level;
56+
}
6657
}
58+
}
59+
return level;
6760
}
61+
}
6862
}

0 commit comments

Comments
 (0)