import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* 思路: 因为要按照顺序打印二叉树,所以在我们输出
* 根节点的值后,需要把当前结点的左右子树保存到队列中。
* 之后再从队列的头中取出结点,一直循环直到全部输出所有结点为止
*
* 采用队列是因为队列是先进先出的结构
*/
public class PrintTtoB_BiTree {
private static Queue<BiTree> queue = new LinkedList<>();
private static int a[] = {1,2,0,4,5,0,0,0,3,6,0,0,0};
static int length = 0;
public static BiTree createBiTree1(BiTree T){
if (length == a.length)
return null;
int value = a[length++] ;
if(value == 0)
T = null;
else{
T = new BiTree();
T.setValue(value);
T.setmLeftChild(createBiTree1(T.mLeftChild));
T.setmRightChild(createBiTree1(T.mRightChild));
}
return T;
}
public static BiTree createBiTree(BiTree root) {
if (length < a.length) {
int value = a[length++];
if (value == 0) {
root = null;
} else {
BiTree lchild = new BiTree();
BiTree rchild = new BiTree();
root.value = value;
root.mLeftChild = createBiTree(lchild);
root.mRightChild = createBiTree(rchild);
}
}
return root;
}
public static void PrintFromToptoBottom(BiTree biTree){
if (biTree == null)
return;
queue.add(biTree);
while (queue.size() > 0){
System.out.println(queue.peek().value);
biTree = queue.peek();
queue.poll();
if(biTree.getmLeftChild() != null)
queue.add(biTree.getmLeftChild());
if(biTree.getmRightChild() != null)
queue.add(biTree.getmRightChild());
}
}
public static void main(String[] args){
BiTree biTree = new BiTree();
createBiTree(biTree);
PrintFromToptoBottom(biTree);
}
static class BiTree{
private int value;
private BiTree mLeftChild;
private BiTree mRightChild;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public BiTree getmLeftChild() {
return mLeftChild;
}
public void setmLeftChild(BiTree mLeftChild) {
this.mLeftChild = mLeftChild;
}
public BiTree getmRightChild() {
return mRightChild;
}
public void setmRightChild(BiTree mRightChild) {
this.mRightChild = mRightChild;
}
}
}
从上到下打印二叉树
最新推荐文章于 2023-04-14 22:28:12 发布