I am working on a task that asks me to implement an AVL tree. I'm sure I have the right rotation methods, but it's hard for me to figure out when to use them.
For example, the explanation in the book says that I have to go up the same path that I went to insert the node / element. However, I cannot have any parent pointers.
Last code:
public BinaryNode<T> insert(BinaryNode<T> node) {
if (this.getElement().compareTo(node.getElement()) > 0) {
if (this.getLeftChild() != null) {
BinaryNode<T> b = this.getLeftChild().insert(node);
if(!this.isBalanced()) {
this.balance();
}
return b;
} else {
this.setLeftChild(node);
}
} else if (this.getElement().compareTo(node.getElement()) < 0) {
if (this.getRightChild() != null) {
return this.getRightChild().insert(node);
} else {
this.setRightChild(node);
}
}
return this;
}
What I want to do is climb the tree, but it can only check the balance AFTER it inserts the node. Therefore, this is in the else clause.
I also tried to enter the balance code, where I suggested R Samuel Klatchko, but checked the balance on each tab. For example: if you insert 7, 9, 5, 3, and 1 sequentially, I get a null pointer exception when trying to insert 1.
EDIT: - , . , (), O (log (n)) AVL.
, ?