BST插入函数导致输出异常(C)
我正在尝试编写一个程序,从文件中获取一个以换行符分隔的字符串列表,然后逐个将它们插入BST 我现在使用的方法导致树中所有节点的值都是添加到树中的最后一个字符串的值 例如,如果插入的列表是:bacedz,则按顺序遍历将树打印为:z 我已经对这段代码进行了多次跟踪,但看不出是什么导致了这一点,我完全陷入了思维障碍 代码如下: 插入.c:BST插入函数导致输出异常(C),c,insert,binary-search-tree,C,Insert,Binary Search Tree,我正在尝试编写一个程序,从文件中获取一个以换行符分隔的字符串列表,然后逐个将它们插入BST 我现在使用的方法导致树中所有节点的值都是添加到树中的最后一个字符串的值 例如,如果插入的列表是:bacedz,则按顺序遍历将树打印为:z 我已经对这段代码进行了多次跟踪,但看不出是什么导致了这一点,我完全陷入了思维障碍 代码如下: 插入.c: #include "node.h" #include <string.h> #include <stdlib.h> #include <
#include "node.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void insert_node(Node* root, char *nextString) {
Node* freshNode;
freshNode = newNode();
freshNode->Word = nextString;
printf("Root->Word = %s\n",root->Word);
printf("nextString = %s\n",freshNode->Word);
int newLessThanRoot = 0;
if (strcmp(root->Word,freshNode->Word) > 0) {
newLessThanRoot = 1;
}
if (newLessThanRoot) {
if (root->Left == NULL) {
root->Left = freshNode;
}
else {
insert_node(root->Left, freshNode->Word);
}
}
if (!newLessThanRoot) {
if (root->Right == NULL) {
root->Right = freshNode;
}
else {
insert_node(root->Right, freshNode->Word);
}
}
}
void inorder(Node *temp) {
if (temp != NULL) {
inorder(temp->Left);
printf("%s ",temp->Word);
inorder(temp->Right);
}
}
您总是插入相同的指针,
inputStrPointer
,实际上是inputString
。hat指针的内容会不断被覆盖,当您最终打印树时,所有节点都会读取最后一行的内容。因此,您应该在树中存储该行的副本。这些副本可以在堆上分配,也可以使用字符数组而不是字符指针作为Word
entry。您总是插入相同的指针inputStrPointer
,实际上就是inputString
。hat指针的内容会不断被覆盖,当您最终打印树时,所有节点都会读取最后一行的内容。因此,您应该在树中存储该行的副本。这些副本可以在堆上分配,也可以使用char数组代替char指针作为Word
entry。
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);