自定义BST删除(C ++)

时间:2016-07-28 16:55:45

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

我实现了一个自定义BST,它将数据存储在叶子中,每个节点代表其子树的最小值。左侧节点存储较高值,右侧节点存储较低值。

然后我通过删除叶子并更新内部节点来删除数据,但不知怎的,我的删除无法正常工作。

这是我的代码,希望你能指出它有问题。非常感谢你。

inline BstNode* BstDelete(BstNode* root, rectangle del){
if (root == NULL) return root;
else if (del > root->data){
    root->left = BstDelete(root->left,del);
    if(root->left == NULL) root->data = root->right->data;
    root->data = root->left->data;
}
else if(del < root->data){
    root->right = BstDelete(root->right,del);
    if (root->right == NULL) root->data = root->left->data;
    root->data = root->right->data;
}
else {
    //found
    //Case1: No Child
    if (root -> left == NULL && root->right == NULL){
        delete root;
        root = NULL;
    }
    //One child
    else if (root->left == NULL){
        root->right = BstDelete(root->right, del);
        if(root->right ==NULL) root = root->right;
        else root->data = root->right->data;
    }
    else if (root->right == NULL){
        root->left = BstDelete(root->left,del);
        if(root->left == NULL) root = root->left;
        else root->data = root->left->data;
    }
    // 2 children
    else {
        root->right = BstDelete(root->right, del);
        if (root->right == NULL) root->data = root->left->data;
        else root->data = root->right->data;

    }
}
return root;}

0 个答案:

没有答案