[LeetCode/111/Java]Minimum Depth of Binary Tree
풀이
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int dept = 0;
while(!queue.isEmpty()) {
dept++;
int size = queue.size();
for(int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if(cur.left == null && cur.right == null) return dept;
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
return dept;
}
}
후기
최소깊이를 찾는 문제입니다.
깊이우선탐색(DFS)를 사용 할 경우 불필요한 탐색이 많아질 가능성이 있다고 생각해서
넓이우선탐색(BFS)방식으로 풀이하였습니다.
time complexity O(N)
space complexity O(N)
728x90
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/113/Java]Path Sum II (0) | 2022.06.05 |
---|---|
[LeetCode/112/Java]Path Sum (0) | 2022.06.05 |
[LeetCode/110/Java]Balanced Binary Tree (0) | 2022.06.05 |
[LeetCode/104/Java]Maximum Depth of Binary Tree (0) | 2022.06.05 |
[LeetCode/101/Java]Symmetric Tree (0) | 2022.06.05 |