Trie模板

本文详细介绍了两种不同的Trie树实现方式:一种是基于字符数组的普通Trie树,另一种则是采用左儿子右兄弟结构的Trie树。通过具体代码展示了如何进行字符串插入和查找操作。

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

普通Trie

const int ALPHABETS=26;
struct TrieNode {
    TrieNode *c[ALPHABETS];
    bool f;

    TrieNode():f(false) {
        memset(c,0,sizeof c);
    }

    ~TrieNode() {
        for(int i=0;i<ALPHABETS;i++)
            if(c[i])
                delete c[i];
    }

    void insert(const char *key) {
        if((*key)==0) {
            f=true;
        } else {
            int Next=((*key)-'A');
            if(c[Next]==NULL) {
                c[Next]=new TrieNode();
            }
            c[Next]->insert(key+1);
        }
    }

    TrieNode *find(const char *key) {
        if((*key)==0) {
            if(f)
                return this;
            else return NULL;
        }
        int Next=((*key)-'A');
        if(c[Next]==NULL) return NULL;
        return c[Next]->find(key+1);
    }
};

左儿子右兄弟

struct TrieNode {
    bool f;
    TrieNode *lc,*rb;
    char ch;

    TrieNode():f(false),lc(0),rb(0),ch(0) {}

    ~TrieNode() {
        delete lc;
        delete rb;
    }

    void insert(const char *key) {
        if((*key)==0) {
            f=true;
        } else {
            TrieNode *pos=lc,*lastpos=0;
            while(pos!=NULL) {
                if(pos->ch==(*key)) break;
                lastpos=pos;
                pos=pos->rb;
            }
            if(pos==NULL) {
                pos=new TrieNode();
                pos->ch=(*key);
                if(lastpos!=NULL)
                    lastpos->rb=pos;
            }
            if(lc==NULL) lc=pos;
            pos->insert(key+1);
        }
    }

    TrieNode *find(const char *key) {
        if((*key)==0) {
            if(this->f)
                return this;
            else return NULL;
        }
        TrieNode *pos=lc;
        while(pos!=NULL && pos->ch!=(*key))
            pos=pos->rb;
        if(pos==NULL) return NULL;
        else return pos->find(key+1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值