Trie树(字典树)的原理及其实现
来源:互联网 发布:深圳网络维护电话 编辑:程序博客网 时间:2024/05/17 02:44
相对来说,Trie树是一种比较简单的数据结构.理解起来比较简单,正所谓简单的东西也得付出代价.故Trie树也有它的缺点,Trie树的内存消耗非常大.当然,或许用左儿子右兄弟的方法建树的话,可能会好点.
其基本性质可以归纳为:
1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3. 每个节点的所有子节点包含的字符都不相同。
搜索字典项目的方法为:
(1) 从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
其他操作类似处理.
/*
Name: Trie树的基本实现
Author: MaiK
Description: Trie树的基本实现 ,包括查找 插入和删除操作*/
#include<algorithm>
#include<iostream>
using namespace std;
const int sonnum=26,base='a';
struct Trie
{
int num;//to remember how many word can reach here,that is to say,prefix
bool terminal;//If terminal==true ,the current point has no following point
struct Trie *son[sonnum];//the following point
};
Trie *NewTrie()// create a new node
{
Trie *temp=new Trie;
temp->num=1;temp->terminal=false;
for(int i=0;i<sonnum;++i)temp->son[i]=NULL;
return temp;
}
void Insert(Trie *pnt,char *s,int len)// insert a new word to Trie tree
{
Trie *temp=pnt;
for(int i=0;i<len;++i)
{
if(temp->son[s[i]-base]==NULL)temp->son[s[i]-base]=NewTrie();
else temp->son[s[i]-base]->num++;
temp=temp->son[s[i]-base];
}
temp->terminal=true;
}
void Delete(Trie *pnt)// delete the whole tree
{
if(pnt!=NULL)
{
for(int i=0;i<sonnum;++i)if(pnt->son[i]!=NULL)Delete(pnt->son[i]);
delete pnt;
pnt=NULL;
}
}
Trie* Find(Trie *pnt,char *s,int len)//trie to find the current word
{
Trie *temp=pnt;
for(int i=0;i<len;++i)
if(temp->son[s[i]-base]!=NULL)temp=temp->son[s[i]-base];
else return NULL;
return temp;
}
转自:http://hi.baidu.com/luyade1987/blog/item/2667811631106657f2de320a.html
- Trie树(字典树)的原理及其实现
- Trie树(字典树)的实现
- Trie树(字典树)的实现
- 字典树(Trie)的java实现
- Trie(字典树)的Java实现
- 字典树 Trie 的实现
- trie字典树实现
- trie(字典树)的双数组实现
- 一个Trie字典树的简单实现
- 实现字典树Trie的基本操作
- 字典树(Trie)的简单实现
- Trie树及其实现
- 7. implement-trie(实现trie字典树)
- Trie树|字典树的简介及实现(转)
- 字典树(Trie树)的C程序实现代码
- Trie树|字典树的简介及实现(转)
- Trie树|字典树的简介及实现(转)
- Trie树(字典树)的C++实现
- HDU 3659 Identify the number(数字识别 模拟)
- opengl: -- 飞机
- 自定义bash shell提示符
- sqlserver2005完整卸载
- 一点记录
- Trie树(字典树)的原理及其实现
- selenium webdriver缺陷
- erlang开发环境配置
- Hibernate get和load区别
- Python调用C/C++的种种方法
- 开篇
- Quartz任务调度
- html5 笔记6 新的form表单处理
- 使用开源组件slidingmenu_library