Trie是一种有效的信息检索数据结构。在上一篇有关trie的文章中,我们讨论了trie的基础知识以及如何在trie中插入和搜索键。在这篇文章中,我们将讨论有关显示Trie的所有内容的信息。也就是说,显示Trie中存在的所有键。
例子:
Input: If Trie is root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
Output: Contents of Trie:
answer
any
bye
their
there
这样做的想法是从trie的根节点开始遍历,每当我们找到NON-NULL子节点时,就在当前索引(级别)的“字符串 str”中添加子节点的父键,然后递归调用对子节点进行相同的处理,然后进行相同的处理,直到找到该节点(即叶节点)为止,该节点实际上标记了字符串。
以下是上述想法的C++实现:
// CPP program to display content of Trie
#include
#include
#define alpha_size 26
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
using namespace std;
// Trie node
struct TrieNode
{
struct TrieNode* children[alpha_size];
bool isLeaf;
};
// Returns new trie node (initialized to NULLs)
struct TrieNode* createNode()
{
struct TrieNode* pNode = new TrieNode;
for (int i = 0; i < alpha_size; i++)
pNode->children[i] = NULL;
pNode->isLeaf = false;
return pNode;
};
// function to insert a node in Trie
void insert_node(struct TrieNode* root, char* key)
{
int level;
int length = strlen(key);
struct TrieNode* pCrawl = root;
for (level = 0; level < length; level++)
{
int index = key[level] - 'a';
if (pCrawl->children[index] == NULL)
pCrawl->children[index] = createNode();
pCrawl = pCrawl->children[index];
}
pCrawl->isLeaf = true;
}
// function to check if current node is leaf node or not
bool isLeafNode(struct TrieNode* root)
{
return root->isLeaf != false;
}
// function to display the content of Trie
void display(struct TrieNode* root, char str[], int level)
{
// If node is leaf node, it indicates end
// of string, so a null character is added
// and string is displayed
if (isLeafNode(root))
{
str[level] = '\0';
cout << str << endl;
}
int i;
for (i = 0; i < alpha_size; i++)
{
// if NON NULL child is found
// add parent key to str and
// call the display function recursively
// for child node
if (root->children[i])
{
str[level] = i + 'a';
display(root->children[i], str, level + 1);
}
}
}
// Driver program to test above functions
int main()
{
// Keys to be inserted in Trie
char keys[][8] = { "the", "a", "there", "answer",
"any", "by", "bye", "their" };
struct TrieNode* root = createNode();
// Inserting keys in Trie
for (int j = 0; j < ARRAY_SIZE(keys); j++)
insert_node(root, keys[j]);
int level = 0;
char str[20];
// Displaying content of Trie
cout << "Content of Trie: " << endl;
display(root, str, level);
}
输出:
Content of Trie:
a
answer
any
by
bye
the
their
there
注意:上面的算法按Lexographically Sorted顺序显示Trie的内容。
Trie的一些有用的应用程序是:
- 实现自动更正和自动完成功能
- 实施字典