class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> rest =new LinkedList<>();
if(root == null) return rest;
Queue<TreeNode> qu = new LinkedList<>();//用于记录每层的值
qu.add(root);//首先将根节点放入队列,也就是第一层
while(qu.size()>0){
int c = qu.size();
List<Integer> temp = new LinkedList<>();
while(c>0){
TreeNode t = qu.poll();
temp.add(t.val);
if(t.left!=null)qu.add(t.left);
if(t.right!=null)qu.add(t.right);
c--;
}
rest.add(temp);
}
return rest;
}
}
因为此时q队列size为1,所以temp只需要添加一个根节点就行
第二层入列
2出列后,加入temp2后,其左右孩子4和5入列
3出列后,加入temp2后,其左右孩子6和7入列
因为此前记录了q队列的长度为2,所以执行2次后,停止进入下一层循环,也就是第三层4次循环,以此类推,记录每一次的temp,假如rest就是得到的结果;