-
Notifications
You must be signed in to change notification settings - Fork 5
/
Solution.java
37 lines (37 loc) · 866 Bytes
/
Solution.java
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
34
35
36
37
/**
* Definition for binary tree
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {
* val = x;
* left=null;
* right=null;
* }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode A) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (A == null) { return res; }
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(A);
while (queue.size() > 0) {
int size = queue.size();
ArrayList<Integer> tmp = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode current = queue.pollLast();
tmp.add(current.val);
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
res.add(tmp);
}
return res;
}
}