250x250
Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
Tags
- priority_queue
- javascript
- Calendar
- deque
- scanner
- Java
- JPA
- BFS
- 스택
- CSS
- List
- 스프링부트
- date
- string
- dfs
- Properties
- NIO
- sql
- math
- union_find
- Union-find
- spring boot
- 힙덤프
- 리소스모니터링
- set
- map
- 큐
- alter
- html
- GC로그수집
Archives
- Today
- Total
매일 조금씩
Leet code (Medium): 102. Binary Tree Level Order Traversal - Java 본문
알고리즘/Tree
Leet code (Medium): 102. Binary Tree Level Order Traversal - Java
mezo 2024. 10. 29. 22:44728x90
반응형
queue를 사용해서 풀면 되는 문제였다.
/**
* 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 List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> output = new ArrayList<>();
if(root == null){
return output;
}
queue.offer(root);
while(!queue.isEmpty()){
int qsize = queue.size();
List<Integer> level = new ArrayList<>();
for(int i = 0; i < qsize; i++){
TreeNode curr = queue.poll();
level.add(curr.val);
if(curr.left != null){
queue.offer(curr.left);
}
if(curr.right != null){
queue.offer(curr.right);
}
}
output.add(level);
}
return output;
}
}
728x90
반응형
'알고리즘 > Tree' 카테고리의 다른 글
Leet code (Easy): 572. Subtree of Another Tree - Java (0) | 2024.10.30 |
---|---|
Leet code (Hard): 297. Serialize and Deserialize Binary Tree - Java (0) | 2024.10.30 |
Leet code (Hard): 124. Binary Tree Maximum Path Sum - Java (1) | 2024.10.29 |
Leet code (Easy): 226. Invert Binary Tree - Java (1) | 2024.10.28 |
Leet code (Easy): 100. Same Tree - Java (0) | 2024.10.28 |