I’m trying to implement AVL. Here’s my insert, balance_tree, check_bf (balance factor), and single left rotate functions in order:
BinaryNode *BinarySearchTree::insert(int x,BinaryNode *t, int dpt) throw(DuplicateItem)
{
if (t == NULL) t = new BinaryNode(x,NULL,NULL,dpt+1);
else if (x < t->element) t->left = insert(x, t->left, dpt+1);
else if (x > t->element) t->right = insert(x, t->right, dpt+1);
else
throw DuplicateItem();
balance_tree(t);
return t;
}
BinaryNode* BinarySearchTree::balance_tree(BinaryNode *t)
{
double debug = check_BF(t);
while(check_BF(t)>1 || check_BF(t)<-1)
{
if(check_BF(t)>1)
{
if(check_BF(t->right)<-1) return doubleLeft(t);
else return singleLeft(t);
}
else if(check_BF(t)<-1)
{
if(check_BF(t->left)>1) return doubleRight(t);
else return singleRight(t);
}
}
}
double BinarySearchTree::check_BF(BinaryNode *t)
{
double l, r;
if(t->left!=NULL) l = t->height(t->left)+1;
else l=0;
if(t->right!=NULL) r = t->height(t->right)+1;
else r=0;
return r-l;
}
BinaryNode* BinarySearchTree::singleLeft(BinaryNode *t)
{
BinaryNode* Y = t;
if(Y!=NULL)
{
t = t->right;
Y->right = t->left;
t->left=Y;
}
return t;
}
I tried it out with a small tree that requires a single left rotation:
1 <----t
\
2
\
3
At the end of the single left rotation function, t points to 2 with 1 as the left node and 3 as the right node, so the function works. The tree looks like this:
2<----t
/ \
1 3
However, when it exits the function, t points to 1 with no left or right node. I don’t understand what happens between that return t and the right bracket } that ends the function that changes t. Can anyone help?
What is missing here is the line in which you call the function in your testing. I think I hear you saying that t is unchanged, but the node to which t points is changed. That the node to which t points (the 1) is changed is the expected behaviour. That t is unchanged is not what you’re expecting. Your routine returns a value. Are you assigning that value to t, or just expecting t to be altered by the routine?