编程语言
首页 > 编程语言> > java实现设计一个二叉树类的结构

java实现设计一个二叉树类的结构

作者:互联网

二叉树是每个节点最多有两个子树的数结构,被常用语实现二茬查找数和二叉堆,使用java可实现设计二叉树的结构 

package treeTest;

import java.util.ArrayList;
import java.util.List;

public class BTree {
    public BTree left;
    public BTree right;
    public BTree root;
    private Object data;
    //节点存入
    public List<BTree> datas;

    public BTree(BTree left,BTree right,Object data){
        this.left = left;
        this.right = right;
        this.data = data;
    }

    public BTree(Object data){
        this(null,null,data);
    }

    public BTree(){}

    public void creat(Object[] obj){
        datas = new ArrayList<BTree>();
        for (Object o : obj) {
            datas.add(new BTree(o));
        }

        root = datas.get(0);

        //建立二叉树
        for (int i = 0; i < obj.length/2; i++) {
            //左子树
            datas.get(i).left = datas.get(i*2+1);
            //右子树
            if(i*2+2<datas.size()){
                datas.get(i) .right = datas.get(i*2+2);
            }
        }
    }

    //递归先序遍历
    public void preOrder(BTree root){
        if (root != null) {
            System.out.println(root.data);
            preOrder(root.left);
            preOrder(root.right);
        }

    }

    //递归中序遍历
    public void inOrder(BTree root){
        if (root != null) {
            inOrder(root.left);
            System.out.println(root.data);
            inOrder(root.right);
        }
    }

    //递归后序遍历
    public void afterOrder(BTree root){
        if (root != null) {
            afterOrder(root.left);
            afterOrder(root.right);
            System.out.println(root.data);
        }
    }

    public static void main(String[] args) {
        BTree bTree = new BTree();
        Object[] a = {'a','b','c','d','e','f','g','h'};
        bTree.creat(a);
        //bTree.preOrder(bTree.root);
        //bTree.inOrder(bTree.root);
        bTree.afterOrder(bTree.root);
    }


}

 

标签:java,Object,二叉树,设计,BTree,data,public,datas,left
来源: https://blog.csdn.net/qq_56467927/article/details/121089792