|
5 | 5 | import java.util.LinkedList;
|
6 | 6 | import java.util.Queue;
|
7 | 7 |
|
8 |
| -/** |
9 |
| - * 111. Minimum Depth of Binary Tree |
10 |
| - * |
11 |
| - * Given a binary tree, find its minimum depth. |
12 |
| - * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. |
13 |
| - * */ |
14 |
| - |
15 | 8 | public class _111 {
|
16 | 9 | public static class Solution1 {
|
17 |
| - /**DFS*/ |
18 |
| - public int minDepth(TreeNode root) { |
19 |
| - if (root == null) { |
20 |
| - return 0; |
21 |
| - } |
22 |
| - int left = minDepth(root.left); |
23 |
| - int right = minDepth(root.right); |
24 |
| - if (left == 0) { |
25 |
| - return right + 1; |
26 |
| - } |
27 |
| - if (right == 0) { |
28 |
| - return left + 1; |
| 10 | + /** |
| 11 | + * DFS |
| 12 | + */ |
| 13 | + public int minDepth(TreeNode root) { |
| 14 | + if (root == null) { |
| 15 | + return 0; |
| 16 | + } |
| 17 | + int left = minDepth(root.left); |
| 18 | + int right = minDepth(root.right); |
| 19 | + if (left == 0) { |
| 20 | + return right + 1; |
| 21 | + } |
| 22 | + if (right == 0) { |
| 23 | + return left + 1; |
| 24 | + } |
| 25 | + return Math.min(left, right) + 1; |
29 | 26 | }
|
30 |
| - return Math.min(left, right) + 1; |
31 |
| - } |
32 | 27 | }
|
33 | 28 |
|
34 |
| - public static class Solution2 { |
35 |
| - /**BFS*/ |
36 |
| - public int minDepth(TreeNode root) { |
37 |
| - if (root == null) { |
38 |
| - return 0; |
39 |
| - } |
40 |
| - Queue<TreeNode> q = new LinkedList(); |
41 |
| - q.offer(root); |
42 |
| - int level = 0; |
43 |
| - while (!q.isEmpty()) { |
44 |
| - level++; |
45 |
| - int size = q.size(); |
46 |
| - for (int i = 0; i < size; i++) { |
47 |
| - TreeNode curr = q.poll(); |
48 |
| - if (curr.left != null) { |
49 |
| - q.offer(curr.left); |
50 |
| - } |
51 |
| - if (curr.right != null) { |
52 |
| - q.offer(curr.right); |
53 |
| - } |
54 |
| - if (curr.left == null && curr.right == null) { |
| 29 | + public static class Solution2 { |
| 30 | + /** |
| 31 | + * BFS |
| 32 | + */ |
| 33 | + public int minDepth(TreeNode root) { |
| 34 | + if (root == null) { |
| 35 | + return 0; |
| 36 | + } |
| 37 | + Queue<TreeNode> q = new LinkedList(); |
| 38 | + q.offer(root); |
| 39 | + int level = 0; |
| 40 | + while (!q.isEmpty()) { |
| 41 | + level++; |
| 42 | + int size = q.size(); |
| 43 | + for (int i = 0; i < size; i++) { |
| 44 | + TreeNode curr = q.poll(); |
| 45 | + if (curr.left != null) { |
| 46 | + q.offer(curr.left); |
| 47 | + } |
| 48 | + if (curr.right != null) { |
| 49 | + q.offer(curr.right); |
| 50 | + } |
| 51 | + if (curr.left == null && curr.right == null) { |
| 52 | + return level; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
55 | 56 | return level;
|
56 |
| - } |
57 | 57 | }
|
58 |
| - } |
59 |
| - return level; |
60 | 58 | }
|
61 |
| - } |
62 | 59 | }
|
0 commit comments