我以前编写过C代码,用于在二进制搜索树中插入和遍历整数值。我试图使它也适用于字符串。我进行了一些更改,例如将所有整数转换为字符串,还添加了诸如strcpy()和strcmp()之类的函数来处理字符串操作。 但是代码似乎不起作用。有人可以向我解释哪里出了问题吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char *str;
struct node *left;
struct node *right;
};
struct node *root=NULL;
void preorder(struct node *temp)
{
if(temp==NULL)
return;
printf("%s ", temp->str);
preorder(temp->left);
preorder(temp->right);
}
void inorder(struct node *temp)
{
if(temp==NULL)
return;
inorder(temp->left);
printf("%s ", temp->str);
inorder(temp->right);
}
void postorder(struct node *temp)
{
if(temp==NULL)
return;
postorder(temp->left);
postorder(temp->right);
printf("%s ", temp->str);
}
struct node* create(char *str) // Function to create new node
{
struct node *new1;
new1=(struct node*)malloc(strlen(str)+10);
strcpy(new1->str,str);
new1->left=NULL;
new1->right=NULL;
return new1;
}
struct node* insert(struct node *root,char *str) // Function to insert a node
{
if(root==NULL)
{
root=create(str);
}
else if(strcmp(str,root->str)<0)
{
root->left = insert(root->left,str);
}
else if(strcmp(str,root->str)>0)
{
root->right = insert(root->right,str);
}
return root;
}
int main()
{
char *str;
while(1)
{
printf("Enter value to insert: ");
scanf("%s",str);
if(strcmp(str,"-1")==0)
{
break;
}
else
{
root=insert(root,str);
}
}
printf("\nThe values of the BST traversed in PREORDER are: ");
preorder(root);
printf("\nThe values of the BST traversed in INORDER are: ");
inorder(root);
printf("\nThe values of the BST traversed in POSTORDER are: ");
postorder(root);
return 0;
}
如果有人可以为我修复此问题,我将不胜感激。
答案 0 :(得分:5)
主要问题:在create
中,您有
new1=(struct node*)malloc(strlen(str)+10);
strcpy(new1->str,str);
您想要一个新节点
new1=(struct node*)malloc(sizeof(node));
字符串的空格
new1->str=malloc(strlen(str)+1); //plus 1 for null terminator
然后您可以执行以下操作:
strcpy(new1->str,str);