Java树的数组简单实现
2017-02-06 16:09
295 查看
对于树这种数据结构:有两种实现方式数组,链表;对于数组的实现方式比较简单
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();
}
}
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();
}
}
相关文章推荐
- java 数组泛型的简单实现
- 利用JAVA数组模拟集合实现简单的对象数组的添加
- 数据结构(java语言描述)-- 表的简单数组实现
- Java蛇形数组的简单实现代码
- Java实现简单的二分法查找int数组中的某值
- Java实现八皇后问题,用数组递归算法,简单易懂
- 简单讲解奇偶排序算法及在Java数组中的实现
- 数据结构笔记--栈的总结及java数组实现简单栈结构
- java数组实现简单的DVD管理
- java字符串数组进行大小排序的简单实现
- java String[]字符串数组自动排序的简单实现
- java中使用数组和链表简单实现SJBMap
- java基础之实现一个简单的数组
- java新手如何简单的理解java数组中冒泡排序法是怎么实现排序的
- [置顶] java使用数组实现简单的Map
- Java版C语言版简单使用静态语言实现动态数组的方法
- java简单实现双色球彩票模拟实例(数组、排序、方法、随机数、键盘输入)
- java中利用IO流实现简单的图书管理系统(利用数组和IO实现)
- 栈--用简单数组实现(Java)
- 队列--基于简单循环数组实现(Java)