/**
* 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>> ans = new ArrayList<>();
while(root==null){
return ans;
}
//建立队列
Queue<TreeNode> q = new LinkedList<>();
//根节点入队列
q.add(root);
while(!q.isEmpty()){
List<Integer> tem = new LinkedList<>();
int size = q.size();
for(int i = 0;i < size;i++){
TreeNode cur = q.poll();
if(cur == null) continue;
tem.add(cur.val);
q.add(cur.left);
q.add(cur.right);
}
if(!tem.isEmpty()){
ans.add(tem);
}
}
return ans;
}
}