Reputation: 109
The following code got me really puzzled.
class
class AVLTree {
private:
struct AVLNode
{
AVLNode *leftchild;
AVLNode *rightchild;
int data;
int height;
};
AVLNode *root;
public:
AVLTree()
{
root = NULL;
}
bool isEmpty() const { return root == NULL; }
void print();
void inorder(AVLNode *n, int l);
void insert(int d);
void rotateLeft(AVLNode* n);
void rotateRight(AVLNode* n);
void rotateLeftTwice(AVLNode* n);
void rotateRightTwice(AVLNode* n);
AVLTree::AVLNode* insert(int d, AVLNode* n);
int max( int a, int b);
int height( AVLNode* n); };
insert function.
AVLTree::AVLNode* AVLTree::insert(int d,AVLNode *n){
if (n == NULL)
{
AVLNode *n = new AVLNode;
n->data = d;
n->leftchild = NULL;
n->rightchild = NULL;
n->height = 0;
} else if( d < n->data) {
n->leftchild = insert(d,n->leftchild);
} else if (d > n->data) {
n->rightchild = insert(d,n->rightchild);
}
else {
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
-----> This section of the code gives be "EXC_BAD_ACCESS".
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
This is the height function.
int AVLTree::height(AVLNode* node)
{ cout << "HEIGHT";
if(node == NULL)
{
return -1;
}
else {
return node->height;
}
}
Anyone knows why?
=== Update:
when doing the rotation
void AVLTree::rotateLeft(AVLNode* n)
{
AVLNode *child = n->leftchild;
n->leftchild = child->rightchild;
child->rightchild = n;
n->height = max(height(n->leftchild),height(n->rightchild))+1;
child->height = max(height(child->leftchild),height(child->rightchild))+1;
n = child;
}
It seems not to be swapping values as it should. While n = child seems to swap locally it does not reflect a change i the rest of the code. Giving me an infinite loop.
Upvotes: 0
Views: 573
Reputation: 254431
If n
was null on entry to the function, then that line will attempt to dereference it, giving the error. Your code to allocate a new node should assign it to n
itself, rather than a separate variable with the same name that shadows the function argument.
Change the first line of the if (n == NULL)
block from
AVLNode *n = new AVLNode;
to
n = new AVLNode;
Regarding the update: In your rotate function, n
is a local (automatic) variable, and changing that won't affect anything outside the function. You will need to either pass the pointer by reference, or return the new pointer value (like you do in insert()
).
Upvotes: 2