BST删除有两个孩子的根节点

时间:2016-06-03 02:22:16

标签: c++ binary-search-tree

我在delete_node中编写了#2的案例但是收到了分段错误。我使用前一个删除节点。我不确定当我删除有两个孩子的根节点时会发生什么。是否与删除有两个孩子的非根节点相同,除非您不必连接前任的孩子?我认为这就是我编码的方式......

bool delete_node(Node*& root, KType key) {

// find target node to delete
Node* target = find(key, root);
if (!target) return false;

// find parent of target
Node* parent = find_parent(root, target);

// case 1: target is a leaf
if (target->left == NULL && target->right == NULL) {
    // set parent's child pointer
    if (parent != NULL) {
        if ( parent->left == target )
            parent->left = NULL;
        else
            parent->right = NULL;
    }
    else
        root = NULL;

    // free target
    delete target;
    return true;
}

// case 2: target has two children
else if (target->left != NULL && target->right != NULL) {
    if (parent != NULL) {
        //find predecessor
        Node* temp = target->left;
        while (temp != NULL) {
            temp = temp->right;
        }

        // find predecessor's parent
        Node* predecessorParent = find_parent(root, temp);

        target->key = temp->key;

        if (predecessorParent->left == temp) {
            predecessorParent->left = temp->left;
        } else {
            predecessorParent->right = temp->left;
        }

        delete(temp);
        return true; // return true when you're done.
    } else {
        //find predecessor
        Node* temp = target->left;
        while (temp != NULL) {
            temp = temp->right;
        }
        target->key = temp->key;
        delete(temp);
        return true; // return true when you're done.
    }
}


// case 3: target has only left child
else if (target->left != NULL) {
    // set parent's child pointer
    if (parent != NULL) {
        if ( parent->left == target )
            parent->left = target->left;
        else
            parent->right = target->left;
    }
    else
        root = target->left;

    // free target
    delete target;
    return true;
}

// case 4: target has only right child
else {
    // set parent's child pointer
    if (parent != NULL) {
        if (parent->left == target)
            parent->left = target->right;
        else
            parent->right = target->right;
    }
    else
        root = target->right;

    // free target
    delete target;
    return true;
}
return false;
}

find_parent函数:

/**
 * Finds the parent of node in the tree rooted at rootNode
 */
Node* find_parent(Node* rootNode, Node* node) {
    if ( rootNode == NULL || rootNode == node ) {
        return NULL;
    }
    else if ( rootNode->left == node || rootNode->right == node ) {
        return rootNode;
    }
    else if (node->key < rootNode->key) {
        return find_parent(rootNode->left, node);
    }
else {
    return find_parent(rootNode->right, node);
    }
}

0 个答案:

没有答案