So I was to implement Splay function after inserting a new tree. However, when I tried to insert multiple ints it says Segmentation Fault (core dump) then exit.
Can anyone check where my problem is?
void SplayTree::splay(Node* node)
{
if (node == NULL)
return;
while (node!=NULL) {
Node* parent = node->parent;
if (parent != NULL) {
if (parent->left == node) {
rightRotate(parent);
} else {
leftRotate(parent);
}
} else {
Node* gparent = parent->parent;
if (parent->left == node && gparent->left == parent) {
rightRotate(gparent);
rightRotate(node->parent);
} else if (parent->right == node &&
gparent->right == parent) {
leftRotate(gparent);
leftRotate(node->parent);
} else if (parent->left == node &&
gparent->right == parent) {
rightRotate(parent);
leftRotate(node->parent);
} else {
leftRotate(parent);
rightRotate(node->parent);
}
}
}
}
On line 15, you have essentially the following sequence of code:
if (parent != NULL) {
...
} else {
Node* gparent = parent->parent;
So essentially you are checking if the parent
is not NULL
, then if it is NULL
you immediately deference it (parent->parent
), you are essentially doing this:
Node* parent = NULL; *parent;
Which is UB, and very likely to cause a segfault.
There are also a series of other deferenced parents
so i think you will need to rethink how your function works.