-2

I'm implementing remove method for binary search tree in C++. In one of cases I am sure that tree node has only one child: node->left or node->right and I need to modify it's parent to point to that child. As I mentioned before one of node->left and node->right are NULL. Here's a snippet:

} else { // One children
  if (node->parent->left == node) {
    node->parent->left = node->left | node->right;
    node->parent->left->parent = node->parent;
  } else {
    node->parent->right = node->left | node->right;
    node->parent->right->parent = node->parent;
  }
}

Unfortunatelly, compiler returns an error. I know that it's maybe not the elegant one but I was just curious how to do it.

keepkimi
  • 373
  • 3
  • 12

2 Answers2

7

Bit manipulation on pointers isn't supported by C++ or C. You can convert them to integers, do the or, then convert back, but that's just asking for trouble for no particular gain.

Use ternary expressions instead:

node->parent->left = node->left ? node->left : node->right;
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

I'm not sure that would achieve what you want. Assigning your pointers the result of a bitwise OR of two other pointers would result in a pointer that points to who knows where.

I think what you are looking for is something like this:

} else { // One children
  if (node->parent->left == node) {
    node->parent->left = node->left != null ? node->left : node->right;
    node->parent->left->parent = node->parent;
  } else {
    node->parent->right = node->left | node->right;
    node->parent->right->parent = node->parent;
  }
}
Mark Erickson
  • 767
  • 1
  • 7
  • 27