import java.util.Arrays;
public class MyTree<T> {
public static final int LEVEL = 10;
//用户存放数据
private Object[] datas;
@SuppressWarnings("unchecked")
MyTree(){
int length = (int) (Math.pow(2, 10) -1);
datas = (T[]) new Object[length];
}
public void setRoot(T obj){
datas[0] = obj;
}
public boolean isEmpty(){
return datas[0] == null;
}
public void addLeft(int index,T obj){
if(index < 0 || index > datas.length){
throw new IndexOutOfBoundsException();
}
if(datas[index] == null){
throw new NullPointerException();
}
datas[2*index + 1] = obj;
}
public void addRight(int index,T obj){
if(index < 0 || index > datas.length){
throw new IndexOutOfBoundsException();
}
if(datas[index] == null){
throw new NullPointerException();
}
datas[2*index + 2] = obj;
}
@SuppressWarnings("unchecked")
public T parent(int index)
{
return (T)datas[(index - 1) / 2] ;
}
@SuppressWarnings("unchecked")
public T getLeft(int index){
if(index < 0 || index > datas.length){
throw new IndexOutOfBoundsException();
}
return (T) datas[2*index + 1] ;
}
@SuppressWarnings("unchecked")
public T getRight(int index){
if(index < 0 || index > datas.length){
throw new IndexOutOfBoundsException();
}
return (T) datas[2*index + 2] ;
}
public static void main(String[] args)
{
MyTree<String> myTree = new MyTree<String>();
myTree.setRoot("root");
myTree.addLeft(0, "leftChild");
myTree.addRight(0, "rightChild");
System.out.println(Arrays.toString(myTree.datas));
}
}
java数组实现的树
最新推荐文章于 2023-06-26 09:46:13 发布