A Za, A Za, Fighting...

坚信:勤能补拙

[zz] Trie树|字典树的简介及实现


Trie,又称字典树、单词查找树,是一种树形结构,用于保存大量的字符串。它的优点是:利用字符串的公共前缀来节约存储空间。
相对来说,Trie树是一种比较简单的数据结构.理解起来比较简单,正所谓简单的东西也得付出代价.故Trie树也有它的缺点,Trie树的内存消耗非常大.当然,或许用左儿子右兄弟的方法建树的话,可能会好点.

其基本性质可以归纳为:
1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3. 每个节点的所有子节点包含的字符都不相同。

其基本操作有:查找 插入和删除,当然删除操作比较少见.我在这里只是实现了对整个树的删除操作,至于单个word的删除操作也很简单.

搜索字典项目的方法为:

(1) 从根结点开始一次搜索;

(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;
(3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。
(4) 迭代过程……
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。
其他操作类似处理.



 1/*
 2Name: Trie树的基本实现 
 3Author: MaiK 
 4Description: Trie树的基本实现 ,包括查找 插入和删除操作*/

 5#include<algorithm>
 6#include<iostream>
 7using namespace std;
 8
 9const int sonnum=26,base='a';
10struct Trie
11{
12    int num;//to remember how many word can reach here,that is to say,prefix
13    bool terminal;//If terminal==true ,the current point has no following point
14    struct Trie *son[sonnum];//the following point
15}
;
16Trie *NewTrie()// create a new node
17{
18    Trie *temp=new Trie;
19    temp->num=1;temp->terminal=false;
20    for(int i=0;i<sonnum;++i)temp->son[i]=NULL;
21    return temp;
22}

23void Insert(Trie *pnt,char *s,int len)// insert a new word to Trie tree
24{
25    Trie *temp=pnt;
26    for(int i=0;i<len;++i)
27    {
28        if(temp->son[s[i]-base]==NULL)temp->son[s[i]-base]=NewTrie();
29        else temp->son[s[i]-base]->num++;
30        temp=temp->son[s[i]-base];
31    }

32    temp->terminal=true;
33}

34void Delete(Trie *pnt)// delete the whole tree
35{
36    if(pnt!=NULL)
37    {
38        for(int i=0;i<sonnum;++i)if(pnt->son[i]!=NULL)Delete(pnt->son[i]);
39        delete pnt; 
40        pnt=NULL;
41    }

42}

43Trie* Find(Trie *pnt,char *s,int len)//trie to find the current word
44{
45    Trie *temp=pnt;
46    for(int i=0;i<len;++i)
47        if(temp->son[s[i]-base]!=NULL)temp=temp->son[s[i]-base];
48        else return NULL;
49    return temp;
50}
 

posted on 2010-11-01 15:28 simplyzhao 阅读(200) 评论(0)  编辑 收藏 引用 所属分类: G_其他


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2024年7月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜