Notice
Recent Posts
Recent Comments
Link
허허의 오늘은 뭐 먹지?
[leetcode] 429. N-ary Tree Level Order Traversal 본문
leetcode.com/problems/n-ary-tree-level-order-traversal/
N-ary Tree Level Order Traversal - 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
이 문제는 bfs의 기본적인 문제입니다.
queue에 시작점을 넣어두고 해당 시작점과 연결된 지점들을 다시 넣어주고를 반복합니다.
반복할 때마다 1depth씩 내려갑니다.
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) {
return result;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
List<Integer> list = new ArrayList<>();
int size = queue.size();
for(int i=0; i<size; i++) {
Node node = queue.poll();
for(Node child : node.children) {
queue.offer(child);
}
list.add(node.val);
}
if(list.size() > 0) {
result.add(list);
}
}
return result;
}
}
반응형
'SW > 알고리즘' 카테고리의 다른 글
876. Middle of the Linked List (0) | 2021.04.08 |
---|---|
[leetcode] 50. Pow(x, n) (0) | 2021.03.04 |
[leetcode] 207. Course Schedule (0) | 2021.03.02 |
[leetcode] 416. Partition Equal Subset Sum (0) | 2021.03.02 |
[leetcode] 56. Merge Intervals (0) | 2021.02.28 |
Comments