forked from jianggao0612/Leetcode_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path111 - Minimum Depth of Binary Tree.java
More file actions
61 lines (45 loc) · 1.61 KB
/
111 - Minimum Depth of Binary Tree.java
File metadata and controls
61 lines (45 loc) · 1.61 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
/**
* 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.
*
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
ArrayList<TreeNode> currentPath = new ArrayList<TreeNode>();
ArrayList<TreeNode> finished = new ArrayList<TreeNode>();
TreeNode node = root;
int minLength = Integer.MAX_VALUE;
if (root == null)
return 0;
if (root.left == null || root.right == null)
return 1;
currentPath.add(root);
while (currentPath.size() > 0) {
node = currentPath.get(currentPath.size() - 1);
if ((node.left != null) && (!finished.contains(node))) {
currentPath.add(node.left);
} else if ((node.right != null) && (!finished.contains(node))) {
currentPath.add(node.right);
} else if ((node.left == null) && (node.right == null)) {
if (currentPath.size() < minLength)
minLength = currentPath.size();
node = currentPath.get(currentPath.size() - 1);
finished.add(node);
currentPath.remove(currentPath.size() - 1);
} else {
node = currentPath.get(currentPath.size() - 1);
finished.add(node);
currentPath.remove(currentPaht.size() - 1);
}
}
return minLength;
}
}