-4

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.

Severage
  • 33
  • 1
  • 7

1 Answers1

1

It looks like the order of operations for all those link changes is incorrect, or you need to store some of those links in local variables before making changes. Work thru it on paper.

The n->get_parent()->set_parent(n); line changes n's grandparent. Following that, calls to n->get_parent()->get_parent() are going to return n. This may be causing loops in your tree.

(I'm assuming that the n->get_parent()>get_parent() is a type, with -> intended instead of a comparison.)

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56