把二叉树按层打印成多行

package com.niuke;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Created by admin on 2018/3/11.
 * 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
 */
public class Print {
    ArrayList<ArrayList<Integer>> print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> alist=new ArrayList<>();//存储最终结果
        if(pRoot==null) {
            return alist;//若为空返回
        }
        LinkedList<TreeNode> queue=new LinkedList<>();//队列
        ArrayList<Integer> list=new ArrayList<>();
        queue.add(pRoot);//将根节点加入队列
        int count=0;//该层的最左节点
        int lastcount=1;//该层的最右节点
        while (queue.size()!=0) {//循环直到队列中没有数
            TreeNode tmp=queue.removeFirst();//移除队头节点并记录
            list.add(tmp.val);
            count++;//该层索引右移
            if(tmp.left!=null) {//该点左子树不为空将其加到队列
                queue.add(tmp.left);
            }
            if(tmp.right!=null) {//该点右子树不为空将其加到队列
                queue.add(tmp.right);
            }
            if(count==lastcount) {//遍历到该层最后一个节点
                lastcount=queue.size();//将最右索引设置为队列的长度,因为现在队列存储的是下一层的所有节点
                count=0;//将最左节点重置就为0
                alist.add(new ArrayList<Integer>(list));//加打结果中
                list.clear();
            }
        }
        return alist;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值