我知道如何使用密钥以传统方式删除节点 . 但是,我需要根据不同的变量(名称)删除节点,然后找到与该变量(名称)匹配的键,并删除包含该变量(名称)的所有节点 . 假设我的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函数的一个问题,但我不知道编写它的最佳方法是让它工作 . 我试图删除一个元素而不直接使用该键 . 如果我要求用户输入而不是在主函数中进行预设,那么阻止它们制作重复键的最佳方法是什么?因为要求用户放置一个不同的密钥,因为它已经存在? (重复的名字没问题) .