【发布时间】:2021-04-06 11:32:12
【问题描述】:
所以我正在尝试解决log2base2.com 中涉及从 BST 中删除节点的问题。除非尝试删除具有两个子节点的节点,否则它可以工作。我知道我可以简单地替换数字,然后在最后删除重复项,但是如果我的结构中的数据不仅仅是key 怎么办?那请问我做错了什么?
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
int getRightMin(struct node *root)
{
//Write your code here
struct node *temp = root;
while(temp->left!=NULL)
{
temp=temp->left;
}
return temp;
}
struct node *removeNode(struct node *root, int key)
{
//Write your code here
if(root == NULL){return NULL;}
if(key<root->key){root->left = removeNode(root->left, key);}
else if(key>root->key){root->right = removeNode(root->right,key);}
else
{
if(root->left==NULL && root->right==NULL)
{
free(root);
return NULL;
}
else if(root->left)
{
struct node *temp = root->left;
free(root);
return temp;
}
else if(root->right)
{
struct node *temp = root->right;
free(root);
return temp;
}
else
{
struct node *temp = getRightMin(root->right);
temp->left = root->left;
temp->right = root->right;
root = temp;
root->right = removeNode(root->right, temp->key);
}
}
return root;
}
//Don't change the below code
struct node *getNewNode(int val)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->key = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node *insert(struct node *root, int val)
{
if(root == NULL)
return getNewNode(val);
if(root->key < val)
root->right = insert(root->right,val);
else if(root->key > val)
root->left = insert(root->left,val);
return root;
}
void inorder(struct node *root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%d ",root->key);
inorder(root->right);
}
int main()
{
struct node *root = NULL;
root = insert(root,100);
root = insert(root,50);
root = insert(root,200);
root = insert(root,150);
root = insert(root,300);
int key;
scanf("%d",&key);
root = removeNode(root,key);
inorder(root);
return 0;
}
测试用例 1:
输入:200
预期输出:50 100 150 300
实际输出:50 100 150
测试用例 2:
输入:100
预期输出:50 150 200 300
实际输出:50
【问题讨论】:
-
请给出准确的输入、预期结果和实际结果。
-
@kaylum 是的,完成了。
-
在 if/else 级联中将大小写
root->left && root->right更高。否则会被if (root->left)捕获,root->right会泄露
标签: c data-structures tree binary-search-tree