tire tree

本文介绍了一个使用C语言实现的Trie树(字典树)数据结构。该实现包括创建节点、插入字符串到树中以及搜索字符串等功能。Trie树是一种用于高效检索字符串的树形数据结构,在搜索引擎、拼写检查等场景中有广泛应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# include <stdio.h>
# include <string.h>
# include <stdlib.h>
typedef struct node{
int cnt;//标记从root->此节点 是否是一个完整的字符串
struct node*child[129];//以ascii码值作为下标
} Node;
Node*create_node()
{
    int i;
    Node*p;
    p = (Node*)malloc(sizeof(Node));
    p->cnt = 0;
    for(i=0;i<129;i++)
    {
        p->child[i] = NULL;
    }
    return p;
}
void insert_node(Node*root,char* str)
{
    Node*p;
    char *s;
    if(root == NULL || *str=='\0') //空字符 或者是 最上层的节点(也就是根节点)不存在
        return;
    s = str;
    while(*s!='\0')
    {
        if(root->child[*s] == NULL)
        {
            p = create_node();
            root->child[*s] = p;
            root = root->child[*s];
        }
        s++;
    }
    root->cnt++;

}
void search_str(Node*root,char*str)
{

    char *s;
    if(root==NULL || *str=='\0')
    {
        printf("tire tree do not exist or string is null!!\n");
    }
    else
    {
        s = str;
        while(*s != '\0')
        {
            if(root->child[*s]!=NULL)
            {
                root = root->child[*s];
            }
            else
            {
                break;
            }
            s++;
        }
    }
    if(root->cnt != 0 )
    {
        if(*s == '\0')
        {
            printf("exist!!\n");
        }
        else
        {
            printf("not exist but is a prefix!!\n");
        }
    }
    else
    {
        if(*s != '\0')
        {
            printf("not exit!!\n");
        }
        else
        {
            if(root->cnt == 0)
            {
                 printf("not exist but is a prefix!!\n");
            }
        }
    }
}
int main()
{
    Node*root;
    char str[100];
    int n;
    root = create_node();//开辟最上层的节点
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",str);
        insert_node(root,str);
    }
    while((scanf("%s",str))!=EOF)
    {
        search_str(root,str);

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值