这道题要写出层来,所以用一个数组来记录层数
初始时将数组全部变成为0,同一时间数组中只有两个数字不为0
前一个表示当前层数还有几个数还没有出队列,后面一个表示下一层有几个数
用一个队列来将二叉树全部装入
1.将roo装入队列,设置数组0号位为1
2.队头出列,将第一个数减一,将队头所有数全部进入队列,进入几个就将第二个数加几,用cnt去控制层数,如果第一个为0,则将两个数互换
3.循环2直至队列为空
public List<List<Integer>> levelOrder(TreeNode root) {
//创建队列,创建cnt去控制层数
Queue<TreeNode> queue= new LinkedList<>();
queue.add(root);
int cnt = 1;
//创建双层list去记录
List<List<Integer>> list = new ArrayList<>();
//root为空直接返回
if(root == null)
return list;
//pre为第一个数,after为第二个数
int pre = 1;
int after = 0;
//栈不为空
while (!queue.isEmpty()){
//换层
List<Integer> list1 = new ArrayList<>();
//第一个数不为0,第一个数为0就说明这一层已经到头了,要换一层
while (pre != 0){
//执行队头出列相关操作
pre --;
//队头出列,并且将队头加入对应的list里面
TreeNode t = queue.remove();
list1.add(t.val);
//出列并且将他的孩子进入
if (t.left!=null){
queue.add(t.left);
after++;
}
if (t.right!=null){
queue.add(t.right);
after++;
}
}
//pre为0,证明要换行,换行交换两个数即可,换行之前一定要保存这一层的list1
list.add(list1);
int tmp = pre;
pre = after;
after = tmp;
}
return list;
}