分行从上往下打印二叉树

分行从上往下打印二叉树

从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。

样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/
12 2
/
6
/
4

输出:[[8], [12, 2], [6], [4]]

在不分行的基础上要在遍历的同时要计算清楚当前层有多少个节点并把他们统一到一个list里

public List<List<Integer>> printFromTopToBottom(TreeNode root) {
        List<List<Integer>> res= new ArrayList<>();//二维链表来保存结果
        if(root==null){//鲁棒
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode head = null;
        int nextnodecount = 1;
        int nodecount = 0;
        while(!queue.isEmpty()){
            nodecount = nextnodecount;//把之前的next给现在的
            nextnodecount = 0;//从新开始计数
            List<Integer> list = new ArrayList<>();//定义这一层的数据集合,根据层数的累加,每次都在更新
            for(int i = 1;i<=nodecount;i++){
               head = queue.poll();
               list.add(head.val);//添加元素到这一层的集合
                if(head.left!=null){
                    queue.offer(head.left);
                    nextnodecount++;

                }
                if(head.right!=null){
                    queue.offer(head.right);
                    nextnodecount++;
                }
            }
            res.add(list);//把这一层的元素集合给最后的结果集合
        }
        return res;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值