【问题标题】:root node automatically resets to null while insertion插入时根节点自动重置为空
【发布时间】: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", &amp;c); 中,您使用了错误的类型或错误的格式说明符。该代码具有未定义的行为,并且可能会因覆盖某些内容而造成损坏。
  • 在相等情况下会发生什么。您测试了if(data &lt; root-&gt;data)if(data &gt; root-&gt;data),但您忽略了data == root-&gt;data
  • 但是在二叉搜索树中,不考虑重复数据。如果data==root-&gt;data 那么我们不应该忽略它吗?并且将 char c 更改为 int c 有效,也许这会导致一些错误

标签: c binary-search-tree


【解决方案1】:

为什么是char c?当您的案例是整数时,请尝试改用int c。此外,您正在使用%d 进行输入,所以它应该是整数

【讨论】:

  • 是的,之前我打算将字符作为输入,但后来我选择整数而不更改它。这是一个愚蠢的错误
  • 如果可行,请接受答案!谢谢!
猜你喜欢
  • 2016-01-17
  • 2019-02-15
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 2011-05-03
  • 2012-11-20
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多