Удалить узел из BST итеративно - PullRequest
0 голосов
/ 18 ноября 2018

Мне нужно удалить узел из BST итеративно. У меня есть пример кода. Удаление листового узла работает отлично, но у меня проблема с одним и двумя дочерними.

давайте проверим наличие дочерних узлов

        if ( temp -> left == NULL && temp -> right == NULL )
        {
            printf("Deleting a leaf.\n");
            if (parent->left == temp)
            {
                parent->left = NULL;
            }
            else
            {
                parent->right = NULL;
            }

            free(temp);
            temp = NULL;
            printf("Set temp null.\n");
            break;
         }else
        if (temp->left == NULL || temp->right == NULL) {
            printf("Deleting a one child.\n");
            //one of the child is null
            if (temp->left != NULL) {
                parent->left = temp->left;
            } else {
                parent->right = temp->right;
            }
            free(temp);
            break;
        } else {
            printf("Deleting two child parent.\n");
            //both of them are not NULL
            //need to find the pre-order successor
            struct node *temp2 = temp->right;

            while (temp2->left != NULL) {
                temp2 = temp2->left;
            }
            //found the successor.
            temp->key = temp2->key;
            free(temp);
            break;
        }
        break;
    }
...