从上到下打印二叉树

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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值