forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_111.java
62 lines (57 loc) · 1.44 KB
/
_111.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
* 111. Minimum Depth of Binary Tree
*
* Given a binary tree, find its minimum depth.
* The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
* */
public class _111 {
public static class Solution1 {
/**DFS*/
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (left == 0) {
return right + 1;
}
if (right == 0) {
return left + 1;
}
return Math.min(left, right) + 1;
}
}
public static class Solution2 {
/**BFS*/
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int level = 0;
while (!q.isEmpty()) {
level++;
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
if (curr.left == null && curr.right == null) {
return level;
}
}
}
return level;
}
}
}