我想从二叉搜索树中删除节点。在此功能中有3个参数。其中一个是树,其他是起始节点和结束节点。我想删除起始节点和结束节点之间的节点。 P.S:用户编写起始节点和结束节点,我们将它们用作参数。
我写的代码:
node * removeReviewsBetween(node * tree,double start,double end){
node * newNode;
if(tree==NULL){
return NULL;
}
if(start< tree->scoreNumber){
tree->left=removeReviewsBetween(tree->left,start,end);
}
else if(start > tree->scoreNumber){
tree->right=removeReviewsBetween(tree->right,start,end);
}
else{
if(tree->right && tree->left){
newNode=findMin(tree->right);
tree->scoreNumber=newNode->scoreNumber;
tree->right=removeReviewsBetween(tree->left,tree->scoreNumber,end);
}
else{
newNode=tree;
if(tree->left==NULL){
tree=tree->right;
}
else if(tree->right==NULL){
tree=tree->left;
}
free(newNode);
}
return tree;
}
}
我写了一些内容,但它确实无法正常工作。请给我一些建议
答案 0 :(得分:0)
应该这样做 - 你的代码稍作修改:
node *removeReviewsBetween(node *tree, double start, double end){
node *newNode;
double score;
if(tree==NULL){
return NULL;
}
while (tree->scoreNumber >= start && tree->scoreNumber =< end){ // if head is in the range to delete
if(tree->right){
newNode = findMin(tree->right);
score = newNode->scoreNumber;
removeReviewsBetween(tree, score, score);
tree->scoreNumber = score;
continue;
}
if(tree->left){
newNode = findMax(tree->left);
score = newNode->scoreNumber;
removeReviewsBetween(tree, score, score);
tree->scoreNumber = score;
continue;
}
return NULL; // if the only node left is the head and it's still in the range to delete
}
if(end < tree->scoreNumber){ // if all nodes to delete are in the left subtree
tree->left = removeReviewsBetween(tree->left, start, end);
return tree;
}
else if(start > tree->scoreNumber){ // if all nodes to delete are in the right subtree
tree->right = removeReviewsBetween(tree->right, start, end);
return tree;
}
}