I am making an Binary Search Tree as an assignment.
I am having problem when i try to add 1,000,000 elements.
I'm getting error after 15,000 elements inserted:
Exception in thread "main" java.lang.StackOverflowError
Something wrong with my code i could not find where i did wrong.
public class BinarytreeInsert {
public static void main(String[] args) {
new BinarytreeInsert().run();
}
static class Node {
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
public void run() {
Node rootnode = new Node(25);
System.out.println("Building tree with root value " + rootnode.value);
System.out.println("=================================");
for(int i = 0 ; i<1_000_000;i++)
insert(rootnode, i);
}
public void insert(Node node, int value) {
if (value < node.value) {
if (node.left != null) {
insert(node.left, value);
} else {
System.out.println(" Inserted " + value + " to left of Node " + node.value);
node.left = new Node(value);
}
} else if (value > node.value) {
if (node.right != null) {
insert(node.right, value);
} else {
System.out.println(" Inserted " + value + " to right of Node " + node.value);
node.right = new Node(value);
}
}
}
}