0

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();
    }
}
Zain Arshad
  • 1,759
  • 1
  • 8
  • 20
Ben Nutter
  • 11
  • 1
  • You need to add some `else` blocks in there. As written, the second and third `if` expressions will still be evaluated when root is null, thus the error when you try to call `getData()` against null. – Idle_Mind Apr 20 '19 at 04:30
  • Your logic definitely isn't right. If the root is null, then why would you assign null to newNode? It should be the other way around; create a new node with your "e" value, and assign that to root. That only takes care of the case where the tree is empty, though. – Idle_Mind Apr 20 '19 at 04:56
  • Yeah, I don't know why I did that instead of setting it to a new AVLNode. Think my brain was just getting fired when I was working on this or something. But now I've realized that it'll want to infinitely insert into the tree now. – Ben Nutter Apr 20 '19 at 05:07
  • OP you should answer the question yourself as you have found the solution.. so that this question don't pop up in other users timeline again and again – Zain Arshad Apr 20 '19 at 10:46

0 Answers0