[英]Find a node in a binary search tree
我的 findNode 在我的插入 function 中被调用,地址为树。 由于我插入的第一个单词树应该是 NULL 但是当我调试它时它会跳过我的 FindWords function 中的这个检查。
如果不是 NULL,我不确定树的确切值是多少,请告知。
struct TREENODE {
struct TREENODE *parent; // point to parent node of this node
struct TREENODE *left; // point to left child of this node
struct TREENODE *right; // point to right child of this node
char *word; // store a unique word in the text file
int count; // num of times this word appears in the file
};
typedef struct TREENODE NODE;
#define MAXWORDLEN 1000
当我插入第一个单词时,树应该是 NULL 因为没有单词存在。 但是,当不存在任何单词时,它不会返回 NULL 而不是这个 function 而是跳到 if 语句 (strcmp(word, tree->word == 0)) 并导致分段错误。
NODE* findNode(char *word, NODE* tree) {
// return node storing word if exists
if (tree == NULL){return NULL;}
if (strcmp(word, tree->word)==0)
return tree;
if (strcmp(word, tree->word) <0)
return findNode(word, tree->left);
return findNode(word, tree->right);
}
void insertNode(char *word, NODE** address_of_tree ) {
NODE *tree = *address_of_tree;
NODE *node;
node = findNode(word, tree);
if (node == NULL) {
NODE *new_node = malloc(sizeof(NODE));
new_node->word = word;
new_node->parent = *address_of_tree;
new_node->left = NULL;
new_node->right = NULL;
if (tree == NULL) {
*address_of_tree = new_node;
return;
}
if (strcmp(word, tree->word) < 0) {
// word must be added to left subtree
if (tree->left !=NULL) insertNode(word, &tree->left);
else {
new_node->parent = tree;
tree->left = new_node;
}
}
else {
if (tree->right != NULL) insertNode(word, &(tree->right));
else {
new_node->parent = tree;
tree->right = new_node;
}
}
}
else {
// update the count for the word
node->count += 1;
}
}
void printTree(NODE* tree) {
// print each word and its count in alphabetical order
if (tree == NULL) return;
printTree(tree->left);
printf("word: %s\ncount: %d", tree->word, tree->count);
printTree(tree->right);
}
int main() {
// read text from stdin
// each time we read a word
// insert this word into the tree
NODE *tree; // the tree we are using to store the words
char word[MAXWORDLEN];
while(scanf("%s", word) != EOF) {
// insert this word into the tree
insertNode(word, &tree);
}
printTree(tree);
return 0;
}
您正在输入缓冲区word
并将其传递给insertNode()
。 在insertNode()
中,您正在做
new_node->word = word;
这将使所有新节点new_node->word
指针指向同一个缓冲区word
。 word
缓冲区内容的任何变化都将反映在所有节点节点nodes->word
值中。 相反,你应该这样做
new_node->word = strdup(word);
strdup()
复制给定的字符串。 它使用malloc
为新字符串获取 memory。 完成后确保释放它。
您还应该在创建树之前使用NULL
初始化tree
NODE *tree = NULL;
因为您将tree
指针传递给insertNode()
并且在insertNode()
中检查tree
指针是否为NULL
。 因此,您应该使用NULL
显式初始化tree
指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.