Hi
I have an array list which has some numbers in it like {23,16,45,26,2,5,9}
and I want to make a binary search tree with this array list which is "array" and its elements are objects that has 2 fields,1)digit2)level but here I just want to use its digit field.Also dList is a DoublyLinkedList.
this is my code but it will throw an exception.please help me , thanks.
private void method(ArrayList<Element> array) {
DNode header = new DNode(null, null, null);
DNode trailer = new DNode(null, header, null);
header.next = trailer;
DNode node = new DNode(array.get(0), header, trailer);
dList.addLast(node);
header = node
for(int i = 1;i<array.size();i++){
makeBST(node, array.get(i));
}
}
private void makeBST(DNode node, Element e) {
if (!e.equals(node.getElement())) {
DNode nodeOne = new DNode(e, null, null);
if (node.getElement().getDigit() > e.getDigit()) {
node.prev = nodeOne;
} else if (node.getElement().getDigit() < e.getDigit()) {
node.next = node;
}
}
if (e.getDigit() < node.getElement().getDigit()) {
makeBST(node.prev, e);
}
makeBST(node.next, e);
}
Exception:
Exception in thread "main" java.lang.StackOverflowError
at OBST.GreedyVersion.makeBST(GreedyVersion.java:43)
at OBST.GreedyVersion.makeBST(GreedyVersion.java:54)
at OBST.GreedyVersion.makeBST(GreedyVersion.java:54)
at OBST.GreedyVersion.makeBST(GreedyVersion.java:54)
the first line of exception is for this line of code:
if (!e.equals(node.getElement()))
your recursive method “private void makeBST(DNode node, Element e)” needs some type of ending condition (a flow path which will prevent it from calling itself); as it is, it keeps calling itself recursively which is what is causing your stack overflow error.