I got stuck on this problem for a little while and I did some research on it. I think they would not solve my situation, so I post my code here. I wrote two functions, both using recursion, however, one of them returns to the last call and the other one returns to the first call.
This is the function that returns to the last call. This code will return the string of the node which associates with the id I passed in. For example, if I pass call getEntry(root,800), I will get "Number 800".
string BST::getEntry(Node * base,int id) {
if (base == nullptr){
return "";
}
if (base->id < id){
base->data = getEntry(base->right,id);
}
if(base->id > id){
base->data = getEntry(base->left,id);
}
return base->data;
}
This function, however, will return to the first call. No matter what number I pass in, it will always return the first base I passed in, which is the root of the tree.
Node *BST::remove(Node* base, int num) {
if (base == nullptr){
return base;
}
else if (num < base->id){
base->left = remove(base->left,num);
}
else if(num > base->id){
base->right = remove(base->right,num);
}
else{
if (base->left == nullptr && base->right == nullptr){
delete base;
base = nullptr;
}
else if(base->left == nullptr){
Node * temp = base;
base = base->right;
delete temp;
}
else if (base->right == nullptr){
Node *temp = base;
base = base->left;
delete temp;
}
else{
Node * temp = findMin(base->right);
base->id = temp->id;
base->data = temp->data;
base->right = remove(base->right,temp->id);
}
}
return base;
}
Aucun commentaire:
Enregistrer un commentaire