forked from algorithm010/algorithm010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC111_min_depth_b_tree.java
More file actions
70 lines (54 loc) · 2.23 KB
/
LC111_min_depth_b_tree.java
File metadata and controls
70 lines (54 loc) · 2.23 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
package Week03;
import Common.BuildBinaryTree;
import Common.TreeNode;
import java.util.Deque;
import java.util.LinkedList;
public class LC111_min_depth_b_tree {
public static void main(String[] args) {
Integer[] list = {3,9,20,1,null,15,7};
TreeNode root = BuildBinaryTree.buildBinaryTree(list);
int res = minDepth(root);
System.out.println("res = "+res);
}
public static int minDepth(TreeNode root) {
if (root == null) return 0;
//1.左孩子和有孩子都为空的情况,说明到达了叶子节点,直接返回1即可
if (root.right == null && root.left == null) return 1;
int leftDep = minDepth(root.left);
int rightDep = minDepth(root.right);
//当节点左右孩子有一个为空时,返回不为空的孩子节点的深度
//as sometimes return leftDep, sometime return rightDep, need to be rightDep +leftDep + 1
//if (root.right == null || root.left == null) return rightDep +leftDep + 1;
// 上面公式其实是如下,root.right == null 时, rightDep=0
if (root.right == null) return leftDep + 1;
if (root.left == null) return rightDep + 1;
//当节点左右孩子都不为空时,返回左右孩子较小深度的节点值
return Math.min(leftDep,rightDep)+1;
}
public int maxDepth_2(TreeNode root) {
if (root == null) return 0;
Deque<TreeNode> queue = new LinkedList<>();
queue.addFirst(root);
int level = 0;
while (!queue.isEmpty()){
level++;
int size = queue.size();
for (int i = 0; i< size; i++){
TreeNode curr = queue.pollLast();
//when left and right chile are null, mean it's a leaf of tree
//we're looking for min, no need to drill down
if (curr.left == null && curr.right == null){
return level;
}
if (curr.left != null) {
queue.addFirst(curr.left);
}
if (curr.right !=null) {
queue.addFirst(curr.right);
}
}
}
//should never reach here.
return -1;
}
}