c - 如何使用二叉搜索树存储字符串?
问题描述
我之前编写过 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;
}
如果有人能为我解决这个问题,我将不胜感激。
解决方案
主要问题:在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);
推荐阅读
- asp.net-mvc - 登录和注册链接从 mvc5 应用程序菜单栏中消失
- node.js - 重放 RPC 调用以进行测试
- linux - 如何在 Linux 上发送请求 POST
- java - 如何在java中从xml节点创建格式化字符串
- r - 将多个 .rda 文件加载到 r 中的列表中
- android - 更新时没有错误,但是图像无法更新android sqlite
- java - 更改 NetBeans 外观的外观
- r - lapply,数据争吵日期,意外输出
- jenkins - 访问先前 Jenkins 构建中哪个阶段失败
- ruby-on-rails - Rails index.html.erb 删除项目 - 不工作