Trie树

Trie树的解释参见:

http://blog.csdn.net/hguisu/article/details/8131559

下面是用C++实现的代码

#ifndef TRIE_H
#define TRIE_H

#define TRIE_SIZE_DEF 128
const int TRIE_SIZE = TRIE_SIZE_DEF;

union NODE_TYPE
{
    COMPLETED;
    UNCOMPLETED;
};

typedef struct Node_
{
    union NODE_TYPE type;
    char ch;
    struct Node_ *child[TRIE_SIZE];
}trie_t;

trie_t * trie_init(void);
void trie_add(trie_t *trie, char *word);
int trie_exists(trie_t *trie, char *word);

#endif // TRIE_H
#include <stdio.h>
#include <stdlib.h>

#include "trie.h"

static trie_t * createNewNode(char ch)
{
    trie_t *newNode = (trie_t *)malloc(sizeof(trie_t));
    newNode->ch = ch;
    newNode->type = UNCOMPLETED;
    int i;
    for(i = 0; i < TRIE_SIZE; i++)
    {
        newNode->child[i] = NULL;
    }
    return newNode;
}

static int char2int(char ch)
{
    return ch - 'a';
}

trie_t * trie_init(void)
{
    return createNewNode('');
}

void trie_add(trie_t *trie, char *word)
{
    char ch;
    while((ch = *word++) != '\0')
    {
        if(trie->child[char2int(ch)] == NULL)
            trie->child[char2int(ch)] = createNewNode(ch);
        trie = trie->child[char2int(ch)];
    }
    trie->type =COMPLETED;
}

int trie_exists(trie_t *trie, char *word)
{
    char ch;
    while((ch = *word++) != '\0')
    {
        if(trie->child[char2int(ch)] == NULL)
            return 0;
        trie = trie->child[char2int(ch)];
    }
    return (trie->tpye == COMPLETED) ? 1 : 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值