I’m currently working on an applet that displays a heap as values are added and removed. I’m implementing the heaps as tree of integers – IntTrees. I’m writing the code for skew heaps, and the ‘add’ method is giving me some trouble. The add method usually works, but once in a while it causes a stack overflow error when a value is added, and I can’t seem to figure out why.
Here’s the code I have written for the add method
‘t’ is an instance variable – the heap itself.
// adds value to heap
public void add(int value) {
IntTree smallTree = new IntTree(value, empty(), empty());
if (t == null) {
t = smallTree;
} else {
t = merge(t, smallTree);
}
}
public IntTree merge(IntTree left, IntTree right) {
if (isEmpty(left)) return right;
if (isEmpty(right)) return left;
int leftVal = left.value();
int rightVal = right.value();
IntTree result;
if (rightVal <= leftVal) {
result = merge(right,left);
} else {
result = left;
if (result.isEmpty(left)) {
result.setLeft(right);
} else {
IntTree temp = result.right();
result.setRight(result.left());
result.setLeft(merge(temp,right));
}
}
return result;
}
Is there something in this code that would cause a stack overflow error, or is the problem perhaps elsewhere in the program? Thanks!
Take a look at this snippet
What happens when
rightVal == leftVal?