Here is my code.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new LinkedList<List<Integer>>();
if (root == null) {
return list;
} else {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
LinkedList<Integer> layers = new LinkedList<>();
while (size != 0) {
TreeNode current = q.poll();
layers.add(current.val);
if (current.left != null) {
q.add(current.left);
}
if (current.right != null) {
q.add(current.right);
}
size--;
}
list.add(layers);
}
}
return list;
}
}
Please let me know if any improvement/correction.