일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 스타벅스
- 백준
- spring
- DP
- 프로그래밍언어론
- 알고리즘
- leetcode
- 백트래킹
- STL
- 시애틀
- 프로그래머스
- 라인
- C/C++
- 머신러닝
- 벤쿠버
- 딥러닝
- 다이나믹프로그래밍
- Python
- binary search
- Java
- 스프링 프레임워크
- Spring Framework
- 릿코드
- 라인플러스
- jvm
- BFS
- dfs
- C++
- 모두를 위한 딥러닝
- 파이썬
Archives
- Today
- Total
케이스윔의 개발 블로그
[Leetcode] 102. Binary Tree Level Order Traversal 본문
문제 정의
root 가 주어졌을 때 레벨 순서대로 순회하며 각 노드의 값을 반환하라.
https://leetcode.com/problems/binary-tree-level-order-traversal
Binary 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
풀이
어제 문제 마저 못풀고 오늘 풀이 쓰기가 살짝 찝찝하지만.. 쉬운 문제라서 먼저 풀었다.
이틀 전 풀었던 문제에서는 각 레벨의 가장 오른쪽 노드값을 차례대로 출력하면 되었는데 오늘 문제는 각 레벨별로 노드의 값을 하나의 List씩 만들어서 List<List<Integer> 를 반환하는 문제이다.
Queue에 자식노드를 추가하면서 레벨 노드를 탐색할 수 있다. 자식 노드를 추가하기 전의 큐의 size는 해당하는 depth에 존재하는 노드개수이므로, 그 size만큼 반복문을 돌면서 노드의 값을 List로 만들어준다.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> nodeQueue = new LinkedList<>();
if (root == null) {
return result;
}
nodeQueue.add(root);
TreeNode curr;
while(!nodeQueue.isEmpty()) {
int size = nodeQueue.size();
List<Integer> nodeList = new ArrayList<>();
for (int i=0; i<size; i++) {
curr = nodeQueue.remove();
nodeList.add(curr.val);
if (curr.left != null) {
nodeQueue.add(curr.left);
}
if (curr.right != null) {
nodeQueue.add(curr.right);
}
}
result.add(nodeList);
}
return result;
}
}
'Algorithm' 카테고리의 다른 글
[Leetcode] 1431. Kids With the Greatest Number of Candies (0) | 2023.04.17 |
---|---|
[Leetcode] 576. Out of Boundary Paths (0) | 2022.07.16 |
[Leetcode] 199. Binary Tree Right Side View (0) | 2022.07.12 |
[Leetcode] 746. Min Cost Climbing Stairs (0) | 2022.07.10 |
[백준][스택] 2504번 괄호의 값 (0) | 2019.02.08 |
Comments