树的节点代表集合
树的边代表关系
字典树代码
查找代码
#include<iostream>
#include<cstdio>
#include<queue>
#include<stack>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<vector>
using namespace std;
#define BASE 26
//字典树节点
class node{
public :
//结点初始化
node(){
flag = false;
for(int i=0;i<BASE;i++) next[i] = nullptr;//每个字典树的next结点设定为空
}
~node(){
delete node;
}
bool flag;//当前节点是否独立成词 (是红色结点还是白色结点)
node *next[BASE];//节点只存储小写字母
};
//定义字典树类
class Trie{
public:
Trie(){
root = new node();//给root分配新的结点空间
}
//传入一个字符串然后插入到字典树中去
bool insert(string word){
//这个方法表示是否是第一次插入这个单词
//定义一个指针变量指向根结点
node *p = root;
for(auto x:word){
//遍历每一个单词字母
int ind = x-'a';
//如果当前节点的边下边没有结点的话新建一个node
if(p->next[ind]==nullptr)p->next[ind]=new node();
p=p->next[ind];
}
if(p->flag) return false;//如果p->flag本身就不为true了说明不是第一次插入这个单词
//插入完单词后需要将单词最后一个节点变成红色
p->flag=true;
return true;
}
//字典树的单词查找操作
bool search(string word){
node *p = root;//字典树操作永远从根结点开始操作因为根结点代表全集
for(auto x:word){
int ind = x-'a';
p = p->next[ind];//p先沿着边向下走一步
if(p==nullptr) return false;//p走到空节点说明字典树中根本就没有这个单词
}
//此时说明我沿着word每一个单词走的不是空节点 需要判断我们当前所在结点是白色还是红色呀, 只有它是红色才证明它是一个独立的单词
return p->flag;
}
static void clearTrie(node *root){
if(root==nullptr)return ;
//否则递归的销毁所有的子树
for(int i=0;i<BASE;i++)clearTrie(root->next[i]);
delete root;
return ;
}
~