Binary Search Tree Node Removal

I am trying to implement a delete function for a binary search tree, but could not get it to work in all cases.

This is my last 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)
    {
        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 in which there is nothing.

I'm just trying to change the values, but getting a runtime error. Any ideas?

edit: I return temp to delete it later.

thank

+3
source share
1 answer

First, your last conditional clause else ifis redundant. Swap it with a sentence else.

-, , , node . find(), node . , , . node , node, node. find() node.

node , . , , . , :

  • node . : , .
  • node node. . node , node .
  • node . node D. D. node R. R D R ( ). , R .

:

         .
        .
       .
      /
     D
    / \
   /\  .
  /  \
 /    \
+------+
        \
         R
        /
       ?
+3

Source: https://habr.com/ru/post/1739745/


All Articles