反复从BST删除节点

时间:2018-11-18 09:21:34

标签: c++ binary binary-search-tree

我需要迭代地从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;
    }

0 个答案:

没有答案