数据结构(四):字典树

一、字典树的性质

        字典树,也称为“前缀树”,是一种特殊的树状数据结构,对于解决字符串相关问题非常有效。典型用于统计、排序、和保存大量字符串。所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

特点:

a)根节点不包含字符,除了根节点每个节点都只包含一个字符。

b)如果当前节点为叶子节点,则从根节点到该节点的字符串起来就是该节点对应的字符串。

c)每个节点的子节点字符不同,也就是找到对应单词、字符是唯一的。

二、字典树的基本操作

#include<iostream>
#include<unordered_map>
using namespace std;

struct TrieNode{
    unordered_map<char, TrieNode*> children;
    bool isword;
    TrieNode()
    {
        isword=false;
    }
};

class TrieTree{
private:
    TrieNode* root;
public:
    TrieTree(){
        root=new TrieNode();
    }
    // 字典树的插入操作
    void insert(string word)
    {
        TrieNode* cur=root;
        for(char c:word)
        {
            if(cur->children.find(c)==cur->children.end())
            {
                cur->children[c]=new TrieNode();
            }
            cur=cur->children[c];
        }
        cur->isword=true;
    }
    // 字典树的搜索操作
    bool search(string word)
    {
        TrieNode* cur=root;
        for(char c:word)
        {
            if(cur->children.find(c)==cur->children.end())return false;
            else cur=cur->children[c];
        }
        return cur->isword;
    }
    
    TrieNode* getroot()
    {
        return root;
    }
};

// 计算字典树总单词数
int countwords(TrieNode* root)
{
    int count=0;
    if(root->isword==true)count++;
    for(auto pair:root->children)
    {
        count+=countwords(pair.second);
    }
    return count;
}

// 打印字典树所有单词
void printwords(TrieNode* curNode,string curWords)
{
    if(curNode->isword)cout<<curWords<<" ";
    for(auto pair:curNode->children)
    {
        printwords(pair.second,curWords+pair.first);
    }
}



int main()
{
    TrieTree trie;
    trie.insert("bad");
    trie.insert("badminton");
    trie.insert("car");
    cout<<"search 'bad':"<<(trie.search("bad")? "Found":"Not Found")<<endl;
    cout<<"search 'cbad':"<<(trie.search("cbad")? "Found":"Not Found")<<endl;
    cout<<"search 'badmin':"<<(trie.search("badmin")? "Found":"Not Found")<<endl;
    cout<<"search 'badminton':"<<(trie.search("badminton")? "Found":"Not Found")<<endl;
    TrieNode* RootNode=trie.getroot();
    cout<<"words number:"<<countwords(RootNode)<<endl;
    cout<<"All words:";
    string current="";
    printwords(RootNode, current);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值