题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

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;
}
全部评论

相关推荐

点赞 评论 收藏
分享
鲸鸿:实习协议不用管签多久,要走的时候提前三天说就可以了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务