So I have this method for the AVL Tree class
that inserts
a new element into the tree. I thought I had the code for it down, but it keeps wanting to throw a NullPointerException
. It starts at the if
condition for when integer e
is less than the root data. Any ideas for what's causing this? I'm not sure at all.
Edit 1: Alright, updated it with else blocks. Not getting the error anymore, but it doesn't seem to be inserting anything into the tree. Feel like I might have missed a step here or there.
Edit 2: Alright, I realized a couple things. First, I was too stupid to realize that for my root == null
I had to set the root to a new AVLNode
with that element, foolish of me. I also realized that, after that, it'll want to infinitely insert into the right side of the tree, at least I think it does.
Edit 3: Turns out, it was my rebalance()
method that was causing the infinite loop. That solved my problem.
public void insert(int e) {
if (root == null) {
root = new AVLNode(e);
}
else if (e < root.getData()) {
root.getLeft().insert(e);
this.rebalance();
this.setHeight();
}
else if (e > root.getData()) {
root.getRight().insert(e);
this.rebalance();
this.setHeight();
}
}