-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution32-2.java
More file actions
33 lines (29 loc) · 951 Bytes
/
Solution32-2.java
File metadata and controls
33 lines (29 loc) · 951 Bytes
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
32
33
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> rowList = new ArrayList<>();
if (root == null) {
return rowList;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> colList = new ArrayList<>();
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
colList.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
rowList.add(colList);
}
return rowList;
}
}