I get an OutOfMemoryError: Java heap space adding an array of sorted elements to array implementation of a binary search tree. I can add arrays of random Integers fine but when I try adding a sorted array I run into this problem. The root of tree is being set to the smallest or largest element of the sorted array, so when you add the rest of the elements I end up with a extremely unbalanced tree which eats up my memory. Any help on this is much appreciated.
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at bst.ArrayBinarySearchTree.resize(ArrayBinarySearchTree.java:386)
at bst.ArrayBinarySearchTree.addElement(ArrayBinarySearchTree.java:26)
at bst.Experiment.main(Experiment.java:90)
public void addElement(T element) {
if(isEmpty()){
count++;
array[1] = element;
}else{
int current = 1;
boolean added = false;
while (!added) {
if(current > (array.length-(array.length*.9))){
resize();
}
if (element.compareTo(array[current]) < 0){
if (array[current*2] == null) {
array[current*2]=element;
added = true;
} else
current = current*2;
} else{
if (array[current*2+1] == null) {
array[current*2+1]=element;
added = true;
} else
current = current*2+1;
}
} //while
}
count++;
}
private void resize(){
T[] temp = (T[])(new Comparable[2*array.length-(array.length/4)]);
for(int i=0; i<array.length; i++)
temp[i] = array[i];
array = temp;
}
well, you will get an unbalanced tree if you dont have balancing in your tree, such as AVL or red black trees. If you are just building a binary search tree without balancing, it s possible that you get a out of memory exception.
I would recommend you to try it with smaller array, to see if you still get a outofmemory exception. if yes, you have a flaw in your code.
I have a binary search tree in c#, take a look at it. Usually you want to use Nodes instead of using an array to represent a binary search tree. As far as i see, you are using a technique which is usually used for heap data structure for heap sort.