剑指offer----把二叉树打印成多行----java实现

利用层次遍历的算法,设置变量last指向当前层的最后一个节点,设置变量count记录当前层已经访问的节点的个数,当count等于last时,表示该层访问结束。

层次遍历在求树的宽度、输出某一层节点,某一层节点个数,每一层节点个数都可以采取类似的算法。

树的宽度:在树的深度算法基础上,加一个记录访问过的层节点个数最多的变量max,在访问每层前maxlast比较,如果max比较大,max不变,如果max小于last,把last赋值给max;

public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) 
    {
        ArrayList<ArrayList<Integer>> list1 = new  ArrayList<ArrayList<Integer>>();
	        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
	       if(pRoot == null)
	       {
	           return list1;
	       }
	        TreeNode current = pRoot;
	        queue.offer(current);
	        int count;//记录当前层已经打印的个数
	        int last;//记录当前层一个有多少个
	        while(!queue.isEmpty())
	        {
	        	count = 0;
	        	last = queue.size();
                ArrayList<Integer> list2 = new ArrayList<Integer>();
	        	//打印一层
	        	while(count < last)
	        	{
	        		current = queue.pop();//出队一个节点并将气质加入到list2中
	        		list2.add(current.val);
	        		count++;//每出队一个几点就增加一个当前层已经打印的节点个数
	        		if(current.left != null)
	        			queue.offer(current.left);
	        		if(current.right != null)
	        			queue.offer(current.right);
	        	}
	        	list1.add(list2);
                
	        }
	       return list1; 
	    }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值