Java树的数组简单实现

对于树这种数据结构:有两种实现方式数组,链表;对于数组的实现方式比较简单




class tree1{

    Object [] datas;
    int sum;
    public tree1() {
        // TODO Auto-generated constructor stub
    }
    //初始化数组的长度
    public tree1(int size){
        this.datas=new Object[size];
        this.sum=size;
    }
    //先确定根节点,才可以接着往下层插入
    public void setRoot(int temp){
        datas[0]=temp;
    }
    //插入左节点,(在插入一个节点时,首先确定这个节点的父节点),index是父节点的数组下标,temp是要插入的数据
    //父亲的左节点:2*index+1;父亲的右节点:2*index+2
    public void setLeft(int index,int temp){
        if(index>sum||index<0){
            throw new IndexOutOfBoundsException();
        }
        datas[2*index+1]=temp;
    }
    public void setRight(int index,int temp){
        if(index>sum||index<0){
            throw new IndexOutOfBoundsException();
        }
        datas[2*index+2]=temp;
    }
    //确定一个节点的父节点
    public int seachPrint(int index){
        return (index-1)/2;
    }
    //有数组构成的树没有前序遍历,中序遍历,后续遍历,只有这一种遍历方法,按照数组下标显示
    public void display(){
        for(int i=0;i<sum;i++){
            System.out.print(datas[i]+" ");
        }
    }
    
}

public class Test1 {

    public static void main(String[] args) {
        tree1 temptree=new tree1(7);
        temptree.setRoot(3);
        temptree.setLeft(0, 5);
        temptree.setRight(0, 7);
        temptree.setLeft(1, 12);
        temptree.setRight(1, 8);
        temptree.setLeft(2, 15);
        temptree.setRight(2, 13);
        //遍历
        temptree.display();

    }

}

猜你喜欢

转载自blog.csdn.net/qq_33500630/article/details/54893985
今日推荐