-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinimumDepthBinaryTree.java
More file actions
59 lines (45 loc) · 1.32 KB
/
Copy pathMinimumDepthBinaryTree.java
File metadata and controls
59 lines (45 loc) · 1.32 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Queue<TreeNode> qu = new LinkedList<>();
Map<TreeNode, TreeNode> parent = new HashMap<>();
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
TreeNode curr = root;
qu.add(curr);
while (!qu.isEmpty()) {
TreeNode next = qu.poll();
if (next.left != null) {
qu.add(next.left);
parent.put(next.left, next);
}
if (next.right != null) {
qu.add(next.right);
parent.put(next.right, next);
}
// found the minimum depth
if (next.left == null && next.right == null) {
if (parent.isEmpty()) {
return 1;
}
int level = 2;
while (parent.get(next) != root){
level++;
next = parent.get(next);
}
return level;
}
}
}
return 0;
}
}