C从BST删除节点而不输入密钥

时间:2018-12-10 03:52:53

标签: c string variables key binary-search-tree

我知道如何使用键以传统方式删除节点。但是,我需要删除基于其他变量(名称)的节点,然后找到与该变量(名称)匹配的键,并删除包含该变量(名称)的所有节点。假设我的insert / inorder / FindMin函数和#include都存在于我的代码中。这是我的代码:

int totalStud;

struct evil {
    int key;
    char name[21];
    struct evil *right;
    struct evil *left;
};



struct evil *Delete(struct evil* root, int key){

    if (root == NULL){
        return root;
    }else if(key<root->key){
        root->left = Delete(root->left, key);
    }else if(key>root->key){
        root->right = Delete(root->right, key);
    }else{
        if (root->left == NULL){
            struct evil *temp = root->right;
            free(temp);
            return temp;
        }else if(root->right == NULL){
            struct evil *temp =  root->left;
            free(temp);
            return temp;
        }
        struct evil *temp = FindMin(root->right);
        root->key = temp->key;
        root->right = Delete(root->right,temp->key);

    }
}

struct evil *DelFinder(struct evil* root, char name[21]){ //I tried several things here, but I don't know what to do here to make it work.
    if (root == NULL){
        return root;
    }
    if(strcmp(root->name, name)==0){
        root = Delete(root, root->key);
        return root;
    }else{
        if (root->left != NULL){
            DelFinder(root->left,name);
        }
        if(root->right != NULL){
            DelFinder(root->right,name);
        }
    }
    return root;
}



int main(void){
    struct evil* root = NULL;

    totalStud = 5;
    root = Insert(root, 1015, "Jack");
    root = Insert(root, 1002, "Bob");
    root = Insert(root, 1085, "Sow");
    root = Insert(root, 1088, "Knack");
    root = Insert(root, 1099, "Sow");

    inorder(root); //all the elements in the BST before deleting Sow

    for (totalStud = 5; totalStud !=-1; totalStud--){
        root = DelFinder(root, "Sow");
    }
    inorder(root); //all the elemennts in BST after deleting Sow

}

我知道DelFinder函数存在问题,但我不知道编写此代码以使其正常工作的最佳方法。我试图删除一个元素而不直接使用键。另外,如果我要求用户输入而不是在主功能中进行预设,那么防止他们进行重复按键的最佳方法是什么?如要求用户输入已存在的其他密钥? (可以使用重复的名称)。

0 个答案:

没有答案