前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >把二叉树打印成多行_60

把二叉树打印成多行_60

作者头像
名字是乱打的
发布2021-12-23 18:34:26
1620
发布2021-12-23 18:34:26
举报
文章被收录于专栏:软件工程
题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

思路

和之字打印二叉树十分类似,不过这里要把实现方式由两个栈实现变成两个队列实现

代码:
代码语言:javascript
复制
  ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<>();

        if (pRoot==null){
            return res;
        }

        Queue<TreeNode> oddQueue=new LinkedList<>();
        Queue<TreeNode> evenQueue=new LinkedList<>();
        oddQueue.add(pRoot);

        //当前遍历奇书行
        boolean isOdd=true;
        //当前遍历的是
        while (!oddQueue.isEmpty()||!evenQueue.isEmpty()){
            ArrayList<Integer> itemRow= new ArrayList<>();

            if (isOdd){
                while (!oddQueue.isEmpty()){
                    final TreeNode poll = oddQueue.poll();
                    itemRow.add(poll.val);
                    if (poll.left!=null){
                        evenQueue.add(poll.left);
                    }
                    if (poll.right!=null){
                        evenQueue.add(poll.right);
                    }
                }
            }else {
                while (!evenQueue.isEmpty()){
                    final TreeNode poll = evenQueue.poll();
                    itemRow.add(poll.val);
                    if (poll.left!=null){
                        oddQueue.add(poll.left);
                    }
                    if (poll.right!=null){
                        oddQueue.add(poll.right);
                    }
                }
            }
            res.add(itemRow);
            isOdd=!isOdd;
            continue;
        }

        return res;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/5/24 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路
    • 代码:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档