此题根前面一道如出一辙,而且更简单一些

把二叉树打印成多行

http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288

public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        ArrayList<Integer> item = new ArrayList<Integer>();
        Queue<TreeNode> q1 = new LinkedList<TreeNode>();
        Queue<TreeNode> q2 = new LinkedList<TreeNode>();
        if(pRoot==null) return res;
        q1.add(pRoot);
        while(true){
            if(q1.isEmpty() && q2.isEmpty()) break;
            if(!q1.isEmpty()){
                while(!q1.isEmpty()){
                    TreeNode temp = q1.poll();
                    item.add(temp.val);
                    if(temp.left!=null) q2.add(temp.left);
                    if(temp.right!=null) q2.add(temp.right);
                }
                res.add(new ArrayList(item));
                item.clear();
            }else{
                while(!q2.isEmpty()){
                    TreeNode temp = q2.poll();
                    item.add(temp.val);
                    if(temp.left!=null) q1.add(temp.left);
                    if(temp.right!=null) q1.add(temp.right);
                }
                res.add(new ArrayList(item));
                item.clear();
            }

        }
        return res;
    }
全部评论

相关推荐

07-16 17:55
门头沟学院 Java
点赞 评论 收藏
分享
07-10 14:08
已编辑
江西农业大学 Java
念旧select:做完把项目放到自己硬盘里给他看,看完拷走
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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