C中的BST - 仅写入root

时间:2017-11-20 13:00:24

标签: c tree binary-tree binary-search-tree

我需要帮助解决一个我不知道原因的问题。 我的代码如下。它只是写了根索引,仅此而已。 root的左右指针仍然是空的。但我分配了内存并将字符串复制到它的索引中。

typedef struct bst {
    char index[128];
    struct bst *left;
    struct bst *right;
}bst;

int main(void)
{
    bst *root = malloc (sizeof(bst));
    root->left = NULL;
    root->right = NULL;
    strcpy(root->index, "indexisnull");

    bst *temp;
    temp = root;

    FILE *fp, *fp2;                         //file pointers
    char word[128];

    fp = fopen("Input1.txt", "r");          //opening text files in read mode
    fp2 = fopen("Input2.txt", "r");

    while(fscanf(fp,"%s", word) == 1) 
    {       
        //getting strings from file to string 'word'        

        temp = root;

        if(strcmp(root->index, "indexisnull") == 0) 
        {
            strcpy(root->index, word);
        }

        if(strcmp(word, root->index) < 0) 
        {
            //temp = temp->left;
            while(temp != NULL) 
            {
                if(strcmp(word, temp->index) < 0) 
                {
                    printf("lefttoleft\n");
                    temp = temp->left;
                }
                else if(strcmp(word, temp->index) > 0) 
                {
                    temp = temp->right;
                    printf("lefttoright\n");
                }
            }
            temp = malloc(sizeof(bst));
            strcpy(temp->index, word);
            temp->left = NULL;
            temp->right = NULL;         
       }
       else if(strcmp(word, root->index) > 0) 
       {
           temp = temp->right;
           while(temp != NULL) 
           {
               if(strcmp(word, temp->index) < 0) 
               {
                   temp = temp->left;
                   printf("righttoleft\n"); 
               }
               else if(strcmp(word, temp->index) > 0)
               {
                   temp = temp->right;
                   printf("righttoright\n");
               }
           }
           temp = malloc(sizeof(bst));
           strcpy(temp->index, word);
           temp->left = NULL;
           temp->right = NULL;
       }
   }

   temp = root;
   printf("%s\n", temp->index);
   printf("%s\n", temp->right->index);
   printf("%s\n", temp->left->index);

   fclose(fp);      //closing files
   fclose(fp2);
   return 0;
}

1 个答案:

答案 0 :(得分:0)

我建议使用gdb来了解您的方法是如何遍历树的。有大量的在线信息可以用它来调试你的程序。尝试在主步和单步执行时设置断点,以便打印临时的内存地址。

我认为你没有为你想要的新bst节点分配内存。当你只有一个根节点时,临界等于什么?根节点需要具有对新分配节点的引用:

NULL

通过在temp-&gt; left或temp-&gt;右分配,父节点存储引用。

至于找到放置节点的适当位置(我给了什么赢得的子节点,它只会存储为左或右子节点)你可以单独跟踪父节点或检查左边/在插入之前右引用为null。