我用C语言写了二进制搜索树,哪个数据是字符串,当我尝试输入数据时遇到问题。
错误显示在第14行,我认为root->data
为NULL导致它,但我不知道如何解决。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
Node *parent;
Node *left;
Node *right;
char *data;
};
Node *insert(Node *root, char *data) {
if (root == NULL) {
Node *tmp;
tmp = (Node *)malloc(sizeof(Node));
root->data = data; // <--- Line 14
tmp -> left = tmp -> right = NULL;
return tmp;
}
if (strcmp(data, root->data) > 0) {
root -> right = insert(root->right, data);
} else if (strcmp(data, root->data) < 0) {
root -> left = insert(root->left, data);
}
return root;
}
void Print(Node *root){
if (root == NULL) return;
Print(root->left);
printf("%s\n", root->data);
Print(root->right);
}
int main() {
Node *root = NULL;
char input[21];
while (scanf("%s", input) != EOF) {
root = insert(root, input);
}
Print(root);
return 0;
}
答案 0 :(得分:1)
在你的功能中:
Node *insert(Node *root, char *data) {
if (root == NULL) {
Node *tmp; // is this really needed?
tmp = (Node *)malloc(sizeof(Node)); // did your mean root = malloc(..) ?
root->data = data; // <--- root is always NULL, from test above
/* ... */