Everytime I add a new node into the tree first it sorts it as a binary tree then recursively look up for violations in AVL.
The problem is in my rotate function I tried to test for the AVL violation which requires a left-left rotation and when I do that by first creating a root, then creating a right child a and then another left child b of a. Now what happens is that it outputs got til the end then I get an error saying:
Exception in thread "main" java.lang.StackOverflowError
at AVLTree$AVLNode.height(AVLTree.java:63)
at AVLTree$AVLNode.height(AVLTree.java:62)
I really don't understand the problem
54 int getBalance(){
55 int leftHeight = (left == null)?0:left.height();
56 int rightHeight = (right == null)?0:right.height();
57
58 return leftHeight - rightHeight;
59 }
61 int height(){
62 int leftHeight = (left == null)?0:left.height();
63 int rightHeight = (right == null)?0:right.height();
return 1 + Math.max(leftHeight, rightHeight);
}
public void rotate(AVLNode test){
System.out.println(test.getBalance());
if(Math.abs(test.getBalance()) < 2){
if(test.getParent() != null){
rotate(test.getParent());
}
else{
return;
}
}
if(test.getBalance() <= -2){
System.out.println(test.getBalance());
if(test.getRight().getBalance() <= 0){
System.out.println("i'm in");
AVLNode parent = test.getParent();
if(parent != null){
if(parent.getLeft() == test){
parent.setLeft(test.getRight());
}
else{
parent.setRight(test.getRight());
}
}
else{
this.root = test.getRight();
}
test.setParent(test.getRight());
if(test.getRight().getLeft() != null){
test.getRight().getLeft().setParent(test);
test.setRight(test.getRight().getLeft());
}
test.getParent().setLeft(test);
System.out.println("got till the end");
}
}
return 1 + Math.max(leftHeight, rightHeight);
the complete code can be this: 'int height(TreeNode tn){ if(tn==null){return 0;}int leftHeight = tn.left.height();
int rightHeight = tn.right.height();
return 1 + Math.max(leftHeight, rightHeight);
}' – nail fei Nov 28 '16 at 02:14