首页 > 解决方案 > 如何使用二叉搜索树存储字符串?

问题描述

我之前编写过 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;
}

如果有人能为我解决这个问题,我将不胜感激。

标签: cstringdata-structuresbinary-treebinary-search-tree

解决方案


主要问题:在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);

推荐阅读