I am trying to insert keys from the first array and sort them into a binary tree in the second array. I know there is a problem with my insert method but I can't figure it out. Any help would be greatly appreciated
import java.util.Arrays;
public class BSTreeArray {
static int startValues[]={50, 25, 75, 10, 15, 5, 53, 29, 79, 78, 111, 33};
int [] aTree;
public BSTreeArray(){
for(int i=0; i<startValues.length;i++){
insert(startValues[i]);
}
System.out.println("Pre-Order:");
preOrder(aTree[0], "");
}
public void insert(int key){
aTree=new int [100];
if(aTree[0]==0){
aTree[0]=key;
}
boolean add = false;
int curIdx=0;
while(!add){
if(key<aTree[curIdx]){
//go left
if (aTree[curIdx*2+1]==0){
aTree[curIdx*2+1]=key;
add = true;
}else{
curIdx=curIdx*2+1;
}
}else{
//go right
if(aTree[curIdx*2+2]==0){
aTree[curIdx*2+2]= key;
add=true;
}else{
curIdx=curIdx*2+2;
}
}
}
}
public void preOrder(int idx, String i){
if(idx>aTree.length){
return;
}else{
System.out.println(i+aTree[idx]);
preOrder(((2*idx)+1), i+".");
preOrder(((2*idx)+2), i+".");
}
}
public static void main (String []args){
BSTreeArray a=new BSTreeArray();
}
}
Current output:
Pre-Order:
0
.0
.0
Desired output:
50
....25
........10
............5
............15
........29
............33
....75
........53
........79
............78
............111