Skip to content

Commit 341a5d3

Browse files
committed
Time: N/A (0%), Space: N/A (0%) - LeetHub
1 parent 2fea48e commit 341a5d3

1 file changed

Lines changed: 43 additions & 14 deletions

File tree

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,54 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
import java.util.*;
17+
118
class Solution {
19+
Queue<TreeNode> queue = new ArrayDeque<>();
20+
221
public int minDepth(TreeNode root) {
3-
if (root == null) return 0;
22+
// //dfs
23+
// if(root == null) return 0;
24+
// int left = minDepth(root.left);
25+
// int right = minDepth(root.right);
26+
27+
// //한쪽 자식이 0이면 null이므로 값이 없다는 소리이므로 반대편 리프노드 값으로 계산
28+
// if(left==0 || right==0) return Math.max(left,right)+1;
29+
30+
// //왼쪽, 오른쪽 자식 모두 값이 있다면, 최솟값으로 계산
31+
// return Math.min(left,right)+1;
32+
33+
//bfs
34+
if(root == null) return 0;
435

5-
Queue<TreeNode> queue = new LinkedList<>();
6-
queue.offer(root);
7-
int depth = 1;
36+
queue.add(root);
37+
int minDepth = 0;
838

9-
while (!queue.isEmpty()) {
10-
int levelSize = queue.size();
39+
while(!queue.isEmpty()){
40+
int queueLen = queue.size();
1141

12-
for (int i = 0; i < levelSize; i++) {
42+
while(queueLen-->0){
1343
TreeNode node = queue.poll();
14-
if (node.left == null && node.right == null)
15-
return depth;
16-
if (node.left != null) queue.offer(node.left);
17-
if (node.right != null) queue.offer(node.right);
44+
if(node.left==null && node.right==null) return minDepth;
45+
if(node.left!=null) queue.add(node.left);
46+
if(node.right!=null) queue.add(node.right);
1847
}
1948

20-
depth++;
21-
}
49+
minDepth++;
50+
}
2251

23-
return depth;
52+
return minDepth;
2453
}
2554
}

0 commit comments

Comments
 (0)