반응형
BFS 문제
leetcode.com/problems/minimum-depth-of-binary-tree/
Minimum Depth of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
루트 노드에서 시작해서 리프 노드까지 가장 짧은 거리를 구하는 문제이다
dfs 문제에서 골랐는데, bfs로 푸는 게 더 적합한 듯하다
해결
BFS로 탐색하다가 자식노드가 없으면 더이상 탐색하지 않는다
private static int bfs(TreeNode root) {
if (root == null) return 0;
Queue<List<TreeNode>> queue = new LinkedList<>();
List<List<TreeNode>> result = new ArrayList<>();
queue.add(List.of(root));
boolean isSearch = false;
while (!queue.isEmpty() && !isSearch) {
List<TreeNode> list = new ArrayList<>();
List<TreeNode> pop = queue.poll();
list.addAll(pop);
List<TreeNode> queueList = new ArrayList<>();
for (TreeNode node : pop) {
if (node.left == null && node.right == null) {
isSearch = true;
break;
}
if (node.left != null) queueList.add(node.left);
if (node.right != null) queueList.add(node.right);
}
if (!queueList.isEmpty()) queue.add(queueList);
if (!list.isEmpty()) result.add(list);
}
return result.size();
}

반응형
'Algorithm > Leetcode' 카테고리의 다른 글
[Leetcode(릿코드)] 378. Kth Smallest Element in a Sorted Matrix (Medium) (0) | 2020.11.03 |
---|---|
[Leetcode(릿코드)] 107. Binary Tree Level Order Traversal II (Easy) (0) | 2020.11.01 |
[Leetcode(릿코드)] 441. Arranging Coins (Easy) (0) | 2020.10.28 |
[Leetcode(릿코드)] 349. Interserction of Two Arrays (Easy) (0) | 2020.10.27 |
[Leetcode(릿코드)] 746. Min Cost Climbing Stairs (Easy) (0) | 2020.10.25 |
댓글