-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-111-Minimum-Depth-of-Binary-Tree.java
More file actions
61 lines (52 loc) · 1.79 KB
/
LeetCode-111-Minimum-Depth-of-Binary-Tree.java
File metadata and controls
61 lines (52 loc) · 1.79 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
/*
LeetCode: https://leetcode.com/problems/minimum-depth-of-binary-tree/
LintCode:
JiuZhang:
ProgramCreek: http://www.programcreek.com/2013/02/leetcode-minimum-depth-of-binary-tree-java/
Analysis:
Depth: # of nodes from root to the leaf(leaf is node whose both right and left are null)
1.DFS(backstrap)
easy
2.BFS(Iterative)
level order traversal and find the first leaf's height (using a count variable as height).
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// DFS
// public int minDepth(TreeNode root) {
// if(root == null) return 0;
// // Find leaf
// if(root.left == null && root.right == null) return 1;
// // if left or right is not null, so it's not leaf
// if(root.left == null) return minDepth(root.right) + 1;
// else if(root.right == null) return minDepth(root.left) + 1;
// else return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
// }
// BFS
public int minDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int count = 1;
while(!queue.isEmpty()){
// List<TreeNode> level = new ArrayList<TreeNode>();
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode curr = queue.poll();
if(curr.left == null && curr.right == null) return count;
if(curr.left != null) queue.add(curr.left);
if(curr.right != null) queue.add(curr.right);
}
count++;
}
return count;
}
}