-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMinimumDepthOfBinaryTree.java
More file actions
81 lines (71 loc) · 2.08 KB
/
Copy pathMinimumDepthOfBinaryTree.java
File metadata and controls
81 lines (71 loc) · 2.08 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package breadthfirstsearch;
// Source : https://leetcode.com/problems/minimum-depth-of-binary-tree/
// Id : 111
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020-01-01
// Topic : Breadth First Search
// Level : Easy
// Other :
// Tips :
// Result : 100.00% 5.33%
import java.util.LinkedList;
import java.util.Queue;
public class MinimumDepthOfBinaryTree {
// 100.00% 0ms 5.33%
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if ((root.left == null) && (root.right == null)) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth(root.right), min_depth);
}
return min_depth + 1;
}
/**
* bfs approach
* @param root
* @return
*/
//
public int minDepth1(TreeNode root) {
// public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
// root 本身就是一层,depth 初始化为 1
int depth = 1;
while (!queue.isEmpty()) {
int size = queue.size();
/* 将当前队列中的所有节点向四周扩散 */
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
/* 判断是否到达终点 */
if (cur.left == null && cur.right == null)
return depth;
/* 将 cur 的相邻节点加入队列 */
if (cur.left != null)
queue.offer(cur.left);
if (cur.right != null)
queue.offer(cur.right);
}
/* 这里增加步数 */
depth++;
}
return depth;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}