I've been trying to implement a delete function for a Binary Search Tree but haven't been able to get it to work in all cases.
This is my latest attempt:
Node* RBT::BST_remove(int c)
{
Node* t = get_node(c);
Node* temp = t;
if(t->get_left() == empty)
*t = *t->get_left();
else if(t->get_right() == empty)
*t = *t->get_right();
else if((t->get_left() != empty) && (t->get_right() != empty))
{
Node* node = new Node(t->get_data(), t->get_parent(), t->get_colour(), t->get_left(), t->get_right());
*t = *node;
}
return temp;
}
Node* RBT::get_node(int c)
{
Node* pos = root;
while(pos != empty)
{
开发者_StackOverflow社区 if(c < pos->get_data())
pos = pos->get_left();
else if(c == pos->get_data())
return pos;
else
pos = pos->get_right();
}
return NULL;
}
t is a node and empty is just a node with nothing in it.
I'm just trying to swap the values but I'm getting a runtime error. Any ideas?
edit: I'm returning temp to delete it afterwards.
Thanks
First, your last else if
conditional clause is redundant. Swap it with an else
clause.
Secondly, I think it would make things easier for you if you'd take as parameter a pointer to the node to remove. You can write a find()
function which would find a node given its key. I'm assuming of course that you can change the function signature. If you can take as parameter the node to remove you can focus on removing the node rather than add logic for finding the node. Otherwise, still write that find()
function and use that for getting the pointer to the relevant node.
When you remove a node in a binary search tree you must maintain the ordering so the tree doesn't lose its integrity. Recall that there is a specific ordering in the tree that supports the fast retrieval of elements. So, enumerate the possible cases:
- The node to delete has no children. That's easy: just release its resources and you're done.
- The node has a single child node. That's fairly simple too. Release the node and replace it with its child, so the child holds the removed node's place in the tree.
- The node has two children. Let's call the node
D
. Find the right-most child ofD
's left subtree. Let's call this nodeR
. Assign the value ofR
toD
, and deleteR
(as described in this algorithm). Notice thatR
can have zero or one children.
The third scenario, illustrated:
.
.
.
/
D
/ \
/\ .
/ \
/ \
+------+
\
R
/
?
精彩评论