【问题标题】:Why is my insert_node function erasing my root? (C)为什么我的 insert_node 函数会擦除我的根? (C)
【发布时间】:2016-02-02 19:07:00
【问题描述】:

我正在尝试编写一个程序,将带有成员字符串的节点插入 BST,然后打印有关该 BST 的信息,例如高度、中序遍历、叶子数等...

截至目前,当我进行中序遍历时,它会打印作为根输入的最后一个字符串,即使它应该位于树的底部。

代码如下:

插入函数:

void insert_node(Node* root, char *nextString) {
    int newLessThanRoot = strcmp( root->Word, nextString ) > 0 ? 1 : 0; // test if nextString is left or right from root

    if (newLessThanRoot && root->Left != NULL) {
      return insert_node(root->Left, nextString);
    }
    if (!newLessThanRoot && root->Right != NULL) {
      return insert_node(root->Right, nextString);
    }

    Node* freshNode = newNode();
    freshNode->Word = malloc(strlen(nextString) +1);
    strcpy(freshNode->Word, nextString);
    freshNode->Left = NULL;
    freshNode->Right = NULL;

    if (newLessThanRoot) {
      root->Left = freshNode;
    }
    else {
      root->Right = freshNode;
    }
}

中序遍历函数:

void inorder(Node *temp) {
  if (temp != NULL) {
    inorder(temp->Left);
    printf("%s ",temp->Word);
    inorder(temp->Right);
  }
}

它们的使用方式:

 char inputString[15];
  char *inputStringPtr = &inputString[0];
  Node* root;
  root = newNode();
  fscanf(infile,"%s",inputStringPtr);
  root->Word = inputString;
  //printf("Root's word: %s\n",root->Word);

  while (fscanf(infile,"%s",inputStringPtr) == 1) {
      insert_node(root,inputStringPtr);
      printf("%s\n",inputString);
  }

  int numberOfStrings = num_of_strings(root);
  int heightOfBST = height_of_tree(root);
  int numberOfLeaves = num_of_leaves(root);

  inorder(root);

输入看起来像这样:

b a c e d l m n o p z

所以输出(进行中序遍历时)应该是:

a b c d e l m n o p z 

但实际上是:

z a c d e l m n o p z

【问题讨论】:

    标签: c binary-search-tree inorder


    【解决方案1】:

    这里读取根节点的值:

    root = newNode();
    fscanf(infile,"%s",inputStringPtr);
    root->Word = inputString;
    

    在这里,你用第二个节点的值再次覆盖它:

    while (fscanf(infile,"%s",inputStringPtr) == 1) {
    

    您可以使用 strdup() 复制根值:

    root->Word = strdup(inputString);
    

    这应该可以解决您的问题。

    insert_node() 中,您正确复制了每个新节点的值。您也可以考虑在那里使用strdup(),而不是 malloc(strlen())/strcpy()。

    【讨论】:

      【解决方案2】:

      您的 inOrder 函数和 insert_node 函数没有问题。使用有一些问题。在行中

       root->Word = inputString;
      

      您正在将本地存储地址分配给 root。随着本地存储的不断变化,词根也会发生变化。

      【讨论】:

      • 啊,非常感谢,修复该行有效,非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多