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