首页 > 其他 > 详细

把二叉树打印成多行

时间:2016-09-02 23:15:36      阅读:140      评论:0      收藏:0      [点我收藏+]

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:需要保存下一层需要打印的节点个数。
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();;
        Queue<TreeNode> queue = new LinkedList<>();
        if(pRoot!=null) {
            queue.add(pRoot);
        }
        int nextLevel = 0;
        int count = 1;
        while(!queue.isEmpty()){
                count--;
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left!=null){
                    queue.add(node.left);
                    nextLevel++;
                }
                if(node.right!=null){
                    queue.add(node.right);
                    nextLevel++;
                }
                if(count == 0){
                    arrayList.add(list);
                    count = nextLevel;
                    nextLevel = 0;
                    list = new ArrayList<Integer>();
                    
                }
        }
        return arrayList;
    }

 

把二叉树打印成多行

原文:http://www.cnblogs.com/yingpu/p/5835771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!