算法导论中对二叉树链表中 Delete 函数的实现

上一篇博客中对 Delete 函数的实现是根据被删除节点子节点的子节点个数, 分为无子节点, 一个子节点和两个子节点的情况分别考虑的。

而这次的代码是根据算法导论的实现用 C++ 直译过来的, 代码如下:

void BinarySearchTree::Delete (const int32_t& value)
{
    auto node = Search (value);
    if (node == nullptr) {
        cerr << "There is no such value!\n";
        return;
    }

    PTreeNode successor = 
        (node->leftChild == nullptr || node->rightChild == nullptr)
            ? node
            : Successor (node);

    
    PTreeNode successorChild =
        (successor->rightChild != nullptr)
            ? successor->leftChild
            : successor->rightChild;

    if (successorChild != nullptr){
        successorChild->parent = successor->parent;
    }

    if (successor->parent.expired()) {
        root = successorChild;
    }
    else {
        auto successorParent = successor->parent.lock ();
        if (successor == successorParent->leftChild) {
            successorParent->leftChild = successorChild;
        }
        else {
            successorParent->rightChild = successorChild;
        }
    }

    if (node != successor) {
        node->key = successor->key;
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。