题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
1. 层序遍历,队列存储元素
2. 标记奇偶层,隔1层做1次数组反转
3. 两层循环:层内循环结束,进入下一层的循环
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot){
ArrayList<ArrayList<Integer>> outArr = new ArrayList<>();
if(pRoot==null)return outArr;//不能返回null
Queue<TreeNode> q = new LinkedList<>();
q.offer(pRoot);
int level = 1;
while(!q.isEmpty()){
int size = q.size();
ArrayList<Integer> inArr = new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode cur = q.poll();
if(cur.left!=null)q.offer(cur.left);
if(cur.right!=null)q.offer(cur.right);
inArr.add(cur.val);
}
if(level%2==0){
Collections.reverse(inArr);
outArr.add(inArr);
}else{
outArr.add(inArr);
}
level++;
}
return outArr;
}
查看12道真题和解析