个人微信公众号:程序员宅急送
百度、Google我相信大家都用过,在搜索框中输入一个字就能弹出很多可选的关键词,如下图
像这种关键词搜索功能最底层的数据结构就是我今天要说的:Trie树。
一、什么是Trie树?
简单点说就是个多叉树。我们把每个字符串中重合的前缀合并在一起形成的多叉树!
二、画个图
说的话有些麻烦,我们直接来看图!
三、代码实现
typedef struct _TrieNode
{
string data;
bool isEnding = false;
struct _TrieNode* children[26] = {0};
}TrieNode;
class Trie
{
public:
TrieNode* initTrie()
{
TrieNode* rootNode = new TrieNode;
rootNode->data = '/';
return rootNode;
}
void insertNode(TrieNode* rootNode,string str)
{
TrieNode* cur = rootNode;
int len = str.size();
for (int i =0;i<len;++i)
{
int index = str[i] - 'a';
if (cur->children[index] != 0)
{
cur = cur->children[index];
}
else
{
TrieNode* newNode = new TrieNode;
newNode->data = str[i];
cur->children[index] = newNode;
cur = newNode;
}
}
cur->isEnding = true;
}
void printTrie(TrieNode* cur,string str)
{
if (cur->isEnding != true)
{
for (int i = 0; i < 26; ++i)
{
if (cur->children[i] != 0)
{
string newStr = str;
newStr += cur->children[i]->data;
printTrie(cur->children[i], newStr);
}
}
}
else
{
cout << str.c_str() << endl;
}
}
void search(TrieNode* rootNode, string str)
{
TrieNode* cur = rootNode;
int len = str.size();
for (int i = 0; i < len; ++i)
{
int index = str[i] - 'a';
if (cur->children[index] != 0)
{
string dd = cur->children[index]->data;
cur = cur->children[index];
}
else
{
cout << "can not find the string."<<endl;
}
}
if (cur->isEnding)
{
cout << str.c_str() << endl;
}
else
{
printTrie(cur, str);
}
}
};
int main()
{
Trie* t1 = new Trie;
TrieNode* root= t1->initTrie();
t1->insertNode(root, "hello");
t1->insertNode(root, "her");
t1->insertNode(root, "hi");
t1->insertNode(root, "how");
t1->insertNode(root, "so");
t1->insertNode(root, "see");
t1->search(root,"he");
system("pause");
return 0;
}