0

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!

Kara
  • 6,115
  • 16
  • 50
  • 57
jordan
  • 9,570
  • 9
  • 43
  • 78
  • 1
    I would suspect using a debugger might tell you whats happening... – Caribou Dec 12 '12 at 22:12
  • 3
    You need to pass the `localRoot` pointer by reference, not by value... The last line has no effect! – Kerrek SB Dec 12 '12 at 22:16
  • @Caribou I know visual studio has a debugger for runtime errors. Unfortunately I don't have access to visual. Know of any in specific that would help? I'm just using a text editor and command line. – jordan Dec 12 '12 at 22:17
  • @Jordy yes windbg (http://msdn.microsoft.com/en-us/windows/hardware/gg463009.aspx) or if you are using cygwin - gdb – Caribou Dec 12 '12 at 22:23
  • http://www.codeproject.com/Articles/6084/Windows-Debuggers-Part-1-A-WinDbg-Tutorial – Caribou Dec 12 '12 at 22:26

1 Answers1

4

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • I made that change, but it's still doing the same thing. It does make sense that passing by reference would have fixed it, but it's still having the same issue. – jordan Dec 12 '12 at 22:23
  • You didn't show you call your function. Thus, it is impossible to tell what is going wrong but I would guess that `localRoot` is coming from an auxiliary pointer in the calling function, too. You need, however, update wherever this pointer is coming from, e.g., the root of the tree (if these three nodes are the entire try) or the parent's corresponding pointer (if these three nodes are a subtree hanging of some node). – Dietmar Kühl Dec 12 '12 at 22:29
  • Yes, you were right. I was calling the rotate in the insert method, where root was being passed as a pointer. Fixed and works. Thank you for your tremendous help! – jordan Dec 12 '12 at 22:42