二进制搜索树无法删除根

时间:2014-05-28 15:59:25

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

这个功能一切正常,但问题是我无法删除根,我无法弄清楚这里的错误是什么。我已经跟踪了"否则部分"它返回工作正常,它返回旧值,我不知道为什么。 Plz帮助!

node *removeNode(node *Root, int key) {

node *tmp = new node;

if(key > Root->value)
    Root->right = removeNode(Root->right,key);

else if(key < Root->value)
    Root->left = removeNode(Root->left, key);

else if(Root->left != NULL && Root->right != NULL) {
    node *minNode = findNode(Root->right);

    Root->value = minNode->value;

    Root->right = removeNode(Root->right,Root->value);
}

else {
    tmp = Root;

    if(Root->left == NULL)
        Root = Root->right;
    else if(Root->right == NULL)
        Root = Root->left;

    delete tmp;
}

return Root;

}

2 个答案:

答案 0 :(得分:0)

更改

removeNode(Root, key);

Root = removeNode(Root, key); 

root文件未被removeNode修改,因为您传递了变量的副本。

答案 1 :(得分:0)

使用此样式,结果是新树,永远不要忘记更新根目录:

Root = removeNode(Root, key);

此外,必须测试空树(Root == NULL)

node *removeNode(node *Root, int key) {

    if(Root == NULL) // Or if(!Root) return Root;
        return NULL;

    if(key > Root->value)
        Root->right = removeNode(Root->right,key);
    else if(key < Root->value)
        Root->left = removeNode(Root->left, key);

    else if(Root->left != NULL && Root->right != NULL) {
        node *minNode = findNode(Root->right); // Left most leaf
        Root->value = minNode->value;
        Root->right = removeNode(Root->right,Root->value);
    }

    else {
        node *found = Rppt;
        if(Root->left == NULL)
            Root = Root->right;
        else if(Root->right == NULL)
            Root = Root->left;
        delete found;
    }

    return Root;
}

替代风格:使用变量别名

removeNode(&Root, key);

void removeNode(node **ptr_var, int key) {
    node *ptr = *ptr_var;
    if (!ptr)
        return;

    if (key > ptr->value)
        removeNode(&ptr->right,key);
    else if(key < ptr->value)
        removeNode(&ptr->left, key);

    else if(ptr->left && ptr->right) {
        node **minNode = &ptr->right;
        while (*minNode) {
            minNode = &(*minNode)->left;
        }
        ptr->value = (*minNode)->value;
        delete *minNode;
        *minNode = NULL;
    }
    else {
        if(! ptr->left)
            *ptr_var = ptr->right;
        else if(!ptr->right)
            *ptr_var = ptr->left;
        delete ptr;
    }
}