Remove from binary search tree

Asked

Viewed 691 times

3

Studying BST (binary search tree) did not understand some parts of the code in the function delete of "mycodeschool".

That part of the code, more specifically:

// Case 1:  No child
    if(root->left == NULL && root->right == NULL) { 
        delete root;
        root = NULL;
    }
//Case 2: One child 
    else if(root->left == NULL) {
        struct Node *temp = root;
        root = root->right;
        delete temp;
    }
  1. I don’t understand why in "Case 1" root can receive NULL after receiving the command delete. I could just put root=NULL and only?

  2. And also in "Case 2" When you delete temp, root is also being deleted, not? since temp has the same address as root.

  3. And I also did not understand the need to delete since there is the command root=root->right.

  4. And why in "Case 1" the delete comes before the main command root=NULL and in "Case 2" delete is after the main command root=root->right?

1 answer

3


1: In the Case 1 you are removing a knot that has no children from either the right or the left. Remove it from memory and arrow like null so that the father of root does not point to a memory site that has been 'displaced';

2 and 3: No, temp has the address of 'old' root for root now it’s pointing to root->right . In the Case 2 he performs the removal operation for us who has only 1 child on the right. When he removes temp from memory, it is removing the old root for root now it’s pointing to the right node so temp points to a node that is not in any tree position being unnecessary to leave it allocated in memory.

4: In the Case 1 was answered in item 1.

In the Case 2, first it takes the content reference to where root is pointing and stores in temp, ago root point to the only child node you have on the right and then remove the temp because he no longer needs it allocated in the mémoria. That is, he takes the reference of root before it points to a new location, and then removes the old content from root.

At this link has some images that will help you better understand this deletion process.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.