【发布时间】:2020-05-21 20:21:13
【问题描述】:
我正在尝试向树中添加新节点,但每当插入完成时,根节点会自动重置为 null,最后我的树为空。我正在尝试构建 BST。 我的主要功能:
int main()
{
char c;
int item;
struct BSTNode *root=NULL;
while(1)
{
printf("\n1 Insert an element ");
printf("\n2 Delete an element");
printf("\n3 InOrder Traversal");
printf("\nEnter your choice: ");
scanf("%d", &c);
switch(c)
{
case 1:
printf("\nEnter the item:");
scanf("%d", &item);
if(root){printf("Root data before: %d",root->data); } //Print statement -1
root = insert(root,item);
printf("Root data after: %d",root->data); //Print statement-2
break;
case 2:
printf("\nEnter the info to be deleted:");
scanf("%d", &item);
root = delete(root, item);
break;
case 3:
InOrder(root);
break;
default:
printf("Enter a valid choice: ");
}
}
return 0;
}
我的插入函数看起来像:
struct BSTNode* insert(struct BSTNode *root, int data)
{
if(root==NULL)
{
root=create(data);
}
if(data<root->data)
root->left=insert(root->left,data);
if(data>root->data)
root->right=insert(root->right,data);
return root;
}
在我的 main 函数中,有两个打印语句。其中,语句 2 正在打印根节点的数据,但是当我想再次添加新节点时,语句 1 不会打印根节点的数据。之后,根节点的新值也显示在语句 2 中。
【问题讨论】:
-
在
scanf("%d", &c);中,您使用了错误的类型或错误的格式说明符。该代码具有未定义的行为,并且可能会因覆盖某些内容而造成损坏。 -
在相等情况下会发生什么。您测试了
if(data < root->data)和if(data > root->data),但您忽略了data == root->data -
但是在二叉搜索树中,不考虑重复数据。如果
data==root->data那么我们不应该忽略它吗?并且将char c更改为int c有效,也许这会导致一些错误
标签: c binary-search-tree