用C++实现Trie树
Trie树,也称为字典树,是一种树型数据结构,主要用于字符串的检索和统计。它可以高效地进行字符串的插入、删除和查找操作,因此被广泛应用于搜索引擎、字符串匹配等领域。
以下是C++实现Trie树的代码示例:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 26; // 字符集大小
struct TrieNode {
int count; // 记录该节点被访问次数
TrieNode *next[MAXN]; // 指向下一个节点的指针数组
TrieNode() {
count = 0;
memset(next, NULL, sizeof(next));
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode *node = root;
for (int i = 0; i < word.size(); i++) {
int index = word[i] - 'a';
if (!node->next[index]) {
node->next[index] = new TrieNode();
}