1. 程式人生 > >關於二叉樹的按層列印

關於二叉樹的按層列印

本文的思路來自於牛客網左程雲大大的二叉樹視訊
視訊地址
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;
    }
}