일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- LeetCode
- Convert Sorted List to Binary Search Tree
- data science
- 운영체제
- concurrency
- Python Implementation
- 43. Multiply Strings
- Python Code
- 30. Substring with Concatenation of All Words
- 시바견
- kaggle
- Decorator
- attribute
- Python
- Protocol
- 컴퓨터의 구조
- shiba
- 109. Convert Sorted List to Binary Search Tree
- Substring with Concatenation of All Words
- DWG
- 프로그래머스
- 715. Range Module
- Class
- Generator
- Regular Expression
- 밴픽
- 파이썬
- 315. Count of Smaller Numbers After Self
- t1
- iterator
Archives
- Today
- Total
Scribbling
[Java 101] 102. Binary Tree Level Order Traversal - Queue 본문
Computer Science/Java
[Java 101] 102. Binary Tree Level Order Traversal - Queue
focalpoint 2023. 3. 4. 04:48
Java STL provides ArrayDeque, LinkedList, and PriorityQueue.
- LinkedList maintains the input order.
- ArrayDeque maintains the input order as well. However, ArrayDeque is more efficient in terms of memory than LinkedList. LinkedList, on the other hand, is efficient when we need to remove elements frequently.
- PriorityQueue maintains the natural order of data.
For BFS, consider using ArrayDeque:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return new ArrayList<>();
List<List<Integer>> ret = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
List<Integer> temp = new ArrayList<>();
int qLen = q.size();
for (int i=0; i<qLen; i++) {
TreeNode node = q.poll();
temp.add(node.val);
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
ret.add(temp);
}
return ret;
}
}
'Computer Science > Java' 카테고리의 다른 글
[Java 101] 211. Design Add and Search Words Data Structure - trie (0) | 2023.03.11 |
---|---|
[Java101] Trie Implementation (0) | 2023.03.08 |
[Java101] LeetCode: 23. Merge k Sorted Lists: Priority Queue (0) | 2023.03.02 |
[Java 101] 20. Valid Parentheses: Stack (0) | 2023.02.23 |
[Java 101] 76. Minimum Window Substring: Set, HashMap (0) | 2023.02.22 |