题目
从上往下打印出二叉树的每个结点,同一层的结点从左到右的顺序打印。
思路
- 要求同一层的结点从左向右顺序打印,可以想到队列;
- 对于根节点,压入队列的顺序是先左结点,后右结点;考虑第二层,左子树的左结点、右结点进入队列,此时队列第一位为右子树根节点,故将右子树的左结点和右结点压入队列,可以看到第三层是有序的
- 按照数学归纳法,假设第k层是有序的,队列中存储着有序的第k层的各个结点,递推到第k+1层时,根据队列先入先出的特性,第k+1层也是有序的。
- 注意边界条件:
仅当结点不为null时将结点压入队列;
输入结点为null。
import datastructure.search.BiTreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class Q23PrintFromTopToBottom {
public static void printFromTopToBottom(BiTreeNode root){
if (root==null)
return;
Queue<BiTreeNode> queue=new LinkedList<BiTreeNode>();
queue.offer(root);
while (!queue.isEmpty()){
BiTreeNode temp=queue.poll();
System.out.println(temp.data);
if (temp.leftChild!=null) {
queue.offer(temp.leftChild);
}
if (temp.rightChild!=null) {
queue.offer(temp.rightChild);
}
}
}
public static void main(String[] args) {
int[] array={3,2,1,4,5};
BiTreeNode root=BiTreeNode.create(array);
printFromTopToBottom(root);
}
}