Java教程

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实现设计一个二叉树类的结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!