关于二叉树的按层打印

本文的思路来自于牛客网左程云大大的二叉树视频
视频地址
http://www.nowcoder.com/courses/1/1/1

题目要求如下:


至于算法分析,大家看视频吧,左老大讲的肯定比我清楚,下面是我实现的代码


class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }

}


public class Solution {
	public static void main(String[] args) {
		TreeNode t1=new TreeNode(1);
		TreeNode t2=new TreeNode(2);
		TreeNode t3=new TreeNode(3);
		TreeNode t4=new TreeNode(4);
		TreeNode t5=new TreeNode(5);
		TreeNode t6=new TreeNode(6);
		TreeNode t7=new TreeNode(7);
		TreeNode t8=new TreeNode(8);
		
		t1.left=t2;  t1.right=t3;
		t2.left=t4;  t3.left=t5; t3.right=t6;
		t5.left=t7;  t5.right=t8;
		new Solution().printFromTopToBottom(t1);
		
	}


    public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
    	ArrayList<Integer> list=new ArrayList<Integer>();
    	Queue <TreeNode> queue=new ArrayBlockingQueue<>(100);
    	TreeNode last=root;     //当前行的最后节点
    	TreeNode nLast=root;    //下一行的最右节点
    	queue.add(root);
    	
    	
    	while (!queue.isEmpty()) {
			TreeNode out=queue.poll();
			System.out.print(out.val+" "); 
			list.add(out.val);
			if (out.left!=null) {
				queue.add(out.left);
				nLast=out.left;
			}
			if (out.right!=null) {
				queue.add(out.right);
				nLast=out.right;
			}
			if (out==last) {
				System.out.println("");
				last=nLast;
			}
			
		}
    	return list;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值