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();

    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值