Hey I am trying to create a balanced binary tree (AVL tree) but seem to run into a problem when I try to rebalance nodes. My node class looks something like this
struct node
{
int val, bal, lsize;
node *left, *right, *parent;
node(): val(0),bal(0),left(NULL),right(NULL),parent(NULL),lsize(0){}
};
val is the node's value, bal is its balance, and lsize is the size of its left subtree.
Here is my method to check a node's balance and then determine which, if any, rotation is to be performed.
void check(node* &n)
{
if(n == NULL)
return;
else
{
if(n->bal > 1)
left_rotate(n);
else if(n->bal < -1)
right_rotate(n);
check(n->parent);
}
}
And here is the method to perform a left rotation. The code for a right rotation is pretty much identical.
void left_rotate(node* &root)
{
node *oldroot=root;
//perform rotation
root=root->right;
oldroot->right=root->left;
root->left=oldroot;
root->parent=oldroot->parent;
oldroot->parent=root;
oldroot->bal -= (1 + max(root->bal, 0));
root->bal -= (1 + min(oldroot->bal, 0));
}
For some reason this seems to be causing an infinite loop, can someone please tell me where the error might be.