面试题:23从上往下打印二叉树

题目:从上往下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印

思路:BFS

public class PrintFromTopToBottom {

	public static void printFromTopToBottom(Node root){
		if(root==null)
			return;
		Queue queue = new ArrayDeque();
		queue.add(root);
		while(!queue.isEmpty()){
			Node temp = queue.poll();
			System.out.print(temp.getData()+" ");
			if(temp.getLeft()!=null)
				queue.add(temp.getLeft());
			if(temp.getRight()!=null)
				queue.add(temp.getRight());
		}
	}

}
class Node{
	private int data;
	private Node left;
	private Node right;
	public Node(int data) {
		super();
		this.data = data;
	}
	public int getData() {
		return data;
	}
	public void setData(int data) {
		this.data = data;
	}
	public Node getLeft() {
		return left;
	}
	public void setLeft(Node left) {
		this.left = left;
	}
	public Node getRight() {
		return right;
	}
	public void setRight(Node right) {
		this.right = right;
	}
	@Override
	public String toString() {
		return "Node [data=" + data + "]";
	}
	public Node() {
		super();
	}
}


你可能感兴趣的:(剑指Offer)