c++data-structuresred-black-treetree-balancing

Red-Black Tree - Rotation Method Implementation - C++


I am implementing a Red-Black tree in c++, but I am having trouble with my rotation methods. The insert method works just fine without any balancing, but as soon as I try to rotate, my tree loses information. My guess is that I'm not setting pointers to the nodes in the right way, but I don't quite understand exactly what is going wrong here.

Here is my rotate right method:

void RedBlackTree::rotateRight(RedBlackNode *localRoot) {
cout << "rotateRight - local root " << localRoot->data << endl;
RedBlackNode *temp = localRoot->left;
localRoot->left = temp->right;
temp->right = localRoot;
localRoot = temp;
}

An example of what is happening is I insert c, b, and a. The tree initially looks like this:

    c
   /
  b
 /
a

After the rotation, the tree will only print out the root node, c.

Any ideas on what may be going on? Thanks!


Solution

  • It's hard to tell based on the code segment but localRoot is a local pointer whose change is forgotten the moment you leave the function. If you want to get it changed in the context where the function is being called from, you either want to pass it as RedBlackNode*& or you should return the value as result.