二叉排序树使用的是二叉链表存储结构, 数据结构如下:
static class DefType{
//前后引用
private DefType pre,after;
//数据
private Integer data = null;
public DefType getPre() {
return pre;
}
public void setPre(DefType pre) {
this.pre = pre;
}
public DefType getAfter() {
return after;
}
public void setAfter(DefType after) {
this.after = after;
}
public Integer getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
@Override
public String toString() {
return "DefType{" +
"pre=" + pre +
", after=" + after +
", data=" + data +
'}';
}
}
创建二叉排序树: 递归创建
public static void createDBT(int org, DefType defType){
//初始化
if( defType.getData()==null){
defType.setData(org);
}else if(org>defType.getData()){
//如果数据大于当前数据,判断是否有右子树
if (defType.getAfter()==null){
//如果没有创建新节点
DefType RdefType = new DefType();
RdefType.setData(org);
defType.setAfter(RdefType);
return;
}
//递归处理
createDBT(org,defType.getAfter());
}else if(org<defType.getData()){
if (defType.getPre()==null){
DefType LdefType = new DefType();
LdefType.setData(org);
defType.setPre(LdefType);
return;
}
createDBT(org,defType.getPre());
}
}
public static void main(String[] args) {
int[] ints = {1,0,2,3,7,8,9,10,11,4,5,6,12,13,14};
DefType defType = new DefType();
for (int i = 0; i < ints.length; i++) {
createDBT(ints[i],defType);
}
System.out.println(defType);
}
二叉遍历: 中序
public static void getOrder(DefType li, List dest){
if (li.getPre()!=null){
getOrder(li.getPre(),dest);
}
if (li.getAfter()!=null){
getOrder(li.getAfter(),dest);
}
dest.add(li.getData());
}