题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ /
6 10
/ / / /
5 7 9 11
输出8 6 10 5 7 9 11。
使用队列,二叉树的广度优先遍历
public class PrintByLevel {
public void printByLevel(BSTreeNode root){
LinkedList<BSTreeNode> q=new LinkedList<BSTreeNode>();
q.addFirst(root);
while(!q.isEmpty()){
BSTreeNode n=q.removeLast();
System.out.print(n.value+" ");
if(n.lefTreeNode!=null) q.addFirst(n.lefTreeNode);
if(n.rightTreeNode!=null)q.addFirst(n.rightTreeNode);
}
}
public static void main(String[] args) {
BSTreeNode root=new BSTreeNode(8);
BSTreeNode p6=new BSTreeNode(6);
BSTreeNode p10=new BSTreeNode(10);
BSTreeNode p5=new BSTreeNode(5);
BSTreeNode p7=new BSTreeNode(7);
BSTreeNode p9=new BSTreeNode(9);
BSTreeNode p11=new BSTreeNode(11);
root.lefTreeNode=p6;
root.rightTreeNode=p10;
p6.lefTreeNode=p5;
p6.rightTreeNode=p7;
p10.lefTreeNode=p9;
p10.rightTreeNode=p11;
PrintByLevel pByLevel=new PrintByLevel();
pByLevel.printByLevel(root);
}
}
class BSTreeNode{
int value;
BSTreeNode lefTreeNode;
BSTreeNode rightTreeNode;
public BSTreeNode(){}
public BSTreeNode(int data){
this.value=data;
}
}
结果:8 6 10 5 7 9 11