I'm working on implementing a splay tree. The insertion works perfectly, but when I try to splay the inserted node in a zig-zig or zig-zag fashion, I always get a segmentation fault. The left-right rotation, used when the node to be splayed has no grandparent, works perfectly.
Here's the code for a right-right zig-zig rotation. If I do, for example
insert("z", 1);
insert("j", 1);
insert("p", 1);
zigZigRotate(root.get_left().get_left());
I get an infinite loop of j's and p's. The first parameter of insert is the key, second is the rank (for an in order traversal).
So, in the previous example, before splaying, the tree would look like: z j p
Since z is inserted at position 1, then j at position 1, moving z to position 2, etc.
Here's the zig-zig code I have for a right-right rotation.
if (n == n->get_parent()->get_left())
{
if (n->get_right() != nullptr)
{
n->get_right()->set_parent(n->get_parent());
}
if (n->get_parent()->get_right() != nullptr)
{
n->get_parent()->get_right()->set_parent(n->get_parent()>get_parent());
}
n->get_parent()->get_parent()->set_parent(n->get_parent());
n->get_parent()->set_parent(n);
n->get_parent()->get_parent()->set_left(n->get_parent()->get_right());
n->get_parent()->set_right(n->get_parent()->get_parent());
n->get_parent()->set_left(n->get_right());
n->set_right(n->get_parent());
n->set_parent(n->get_parent()->get_parent()->get_parent());
}
I've traced it, and it seems like it should be rotating correctly to me. No place where an infinite loop should happen. But since it is, I would assume j and p are connected together somehow in a way they shouldn't be. Such as j has p as its left child, but p has j as one of its children for some reason.