Trie树的C++实现

来源:互联网 发布:阿里云系统3.2.0刷机 编辑:程序博客网 时间:2024/05/22 17:30

转自:http://blog.csdn.net/insistgogo/article/details/7828851

作者: insistGoGo

一、定义:

        Trie,又称字典树,是一种用于快速检索的二十六叉树结构。典型的空间换时间

二、结构图:

           

三、原理:

       Trie把要查找的关键词看作一个字符序列,并根据构成关键词字符的先后顺序检索树结构;

        特别地:和二叉查找树不同,在Trie树中,每个结点上并非存储一个元素。

四、性质:

       0、利用串的公共前缀,节约内存

       1、在trie树上进行检索总是始于根结点

       2、根节点不包含字符,除根节点外的每一个节点都只代表一个字母,这里不是包含。

       3、从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

       4、每个节点的所有子节点包含的字符都不相同。

五、效率分析

       0、当存储大量字符串时,Trie耗费的空间较少。因为键值并非显式存储的,而是与其他键值共享子串。

       1、查询快。在trie树中查找一个关键字的时间和树中包含的结点数无关,而取决于组成关键字的字符数。对于长度为m的键值,最坏情况下只需花费O(m)的时间(对比:二叉查找树的查找时间和树中的结点数有关O(log2n)。)

       2、如果要查找的关键字可以分解成字符序列且不是很长,利用trie树查找速度优于二叉查找树。

       3、若关键字长度最大是5,则利用trie树,利用5次比较可以从265=11881376个可能的关键字中检索出指定的关键字。而利用二叉查找树至少要进行log2265=23.5次比较。

六、应用:用于字符串的统计与排序,经常被搜索引擎系统用于文本词频统计。

      1、字典树在串的快速检索中的应用。

      给出N个单词组成的熟词表,以及一篇全用小写英文书写的文章,请你按最早出现的顺序写出所有不在熟词表中的生词。在这道题中,我们可以用字典树,先把熟词建一棵树,然后读入文章进行比较,这种方法效率是比较高的。

      2、字典树在“串”排序方面的应用

      给定N个互不相同的仅由一个单词构成的英文名,让你将他们按字典序从小到大输出用字典树进行排序,采用数组的方式创建字典树,这棵树的每个结点的所有儿子很显然地按照其字母大小排序。对这棵树进行先序遍历即可。

      3.、字典树在最长公共前缀问题的应用

      对所有串建立字典树,对于两个串的最长公共前缀的长度即他们所在的结点的公共祖先个数,于是,问题就转化为最近公共祖先问题。

代码

[cpp] view plaincopyprint?
  1. #ifndef _TRIE_  
  2. #define _TRIE_  
  3.   
  4. #include <iostream>  
  5. #include <fstream>  
  6. #include <string>  
  7. #include <algorithm>  
  8. #include <assert.h>  
  9. using namespace std;  
  10. const int MaxBranchNum = 26;//如果区分大小写,可以扩展到52  
  11.   
  12. /*定义trie树结点*/  
  13. class TrieNode  
  14. {  
  15. public:  
  16.     char* word; //节点表示的单词  
  17.     int count;  //单词出现的次数  
  18.     TrieNode* nextBranch[MaxBranchNum];//指向26个字符节点的指针  
  19. public:  
  20.     TrieNode() : word(NULL),count(0)  
  21.     {  
  22.         memset(nextBranch,NULL,sizeof(TrieNode*) * MaxBranchNum);  
  23.     }  
  24. };  
  25.   
  26. /*定义类Trie*/  
  27. class Trie  
  28. {  
  29. public:  
  30.     Trie();  
  31.     ~Trie();  
  32.     void Insert(const char* str);//插入字符串str  
  33.     bool Search(const char* str,int& count);//查找字符串str,并返回出现的次数  
  34.     bool Remove(const char* str);//删除字符串str  
  35.     void PrintALL();//打印trie树中所有的结点  
  36.     void PrintPre(const char* str);//打印以str为前缀的单词  
  37. private:  
  38.     TrieNode* pRoot;  
  39. private:  
  40.     void Destory(TrieNode* pRoot);  
  41.     void Print(TrieNode* pRoot);  
  42. };  
  43.   
  44. #endif //_TRIE_  
  45.   
  46. Trie::Trie()  
  47. {  
  48.     pRoot = new TrieNode();//注意字典树的根不存放字符  
  49. }  
  50.   
  51. Trie::~Trie()  
  52. {  
  53.     Destory(pRoot);  
  54. }  
  55.   
  56. /*插入一个单词*/  
  57. void Trie::Insert(const char* str)  
  58. {  
  59.     assert(NULL != str);  
  60.     int index;  
  61.     TrieNode* pLoc = pRoot;  
  62.     for (int i = 0;str[i];i++)  
  63.     {  
  64.         index = str[i] - 'a';//如果区分大小写,可以扩展  
  65.   
  66.         if(index < 0 || index > MaxBranchNum)//不执行插入  
  67.         {  
  68.             return;  
  69.         }  
  70.   
  71.         if (NULL == pLoc->nextBranch[index])//该单词的前缀不存在,要生成该结点  
  72.         {  
  73.             pLoc->nextBranch[index] = new TrieNode();  
  74.         }  
  75.         pLoc = pLoc->nextBranch[index];  
  76.     }  
  77.     if (NULL != pLoc->word)//单词已经出现过  
  78.     {  
  79.         pLoc->count++;  
  80.         return;  
  81.     }  
  82.     else    //单词没有出现过,应该插入单词  
  83.     {  
  84.         pLoc->count++;  
  85.         pLoc->word = new char[strlen(str) + 1];  
  86.         assert(NULL != pLoc->word);  
  87.         strcpy(pLoc->word,str);  
  88.     }  
  89. }  
  90.   
  91. /*查找一个单词,如果存在该单词,则返回其出现次数*/  
  92. bool Trie::Search(const char* str,int& count)  
  93. {  
  94.     assert(str != NULL);  
  95.     int i = 0;  
  96.     int index = -1;;  
  97.     TrieNode* pLoc = pRoot;  
  98.     while(pLoc && *str)  
  99.     {  
  100.         index = *str - 'a';//如果区分大小写,可以扩展  
  101.   
  102.         if(index < 0 || index > MaxBranchNum)//不是一个单词,不执行插入  
  103.         {  
  104.             return false;  
  105.         }  
  106.   
  107.         pLoc = pLoc->nextBranch[index];  
  108.         str++;  
  109.     }  
  110.     if (pLoc && pLoc->word)//条件成立,找到该单词  
  111.     {  
  112.         count = pLoc->count;  
  113.         return true;  
  114.     }  
  115.     return false;  
  116. }  
  117.   
  118. bool Trie::Remove(const char* str)  
  119. {  
  120.     assert(NULL != str);  
  121.     int index = -1;;  
  122.     TrieNode* pLoc = pRoot;  
  123.     while(pLoc && *str)  
  124.     {  
  125.         index = *str - 'a';//如果区分大小写,可以扩展  
  126.   
  127.         if(index < 0 || index > MaxBranchNum)//不是一个单词,不执行插入  
  128.         {  
  129.             return false;  
  130.         }  
  131.   
  132.         pLoc = pLoc->nextBranch[index];  
  133.         str++;  
  134.     }  
  135.     if (pLoc && pLoc-> word)//条件成立,找到该单词  
  136.     {  
  137.         delete[] pLoc->word;  
  138.         pLoc->word = NULL;  
  139.         return true;  
  140.     }  
  141.     return false;  
  142. }  
  143.   
  144. void Trie::PrintALL()  
  145. {  
  146.     Print(pRoot);  
  147. }  
  148.   
  149. void Trie::PrintPre(const char* str)  
  150. {  
  151.     assert(str != NULL);  
  152.     int i = 0;  
  153.     int index = -1;;  
  154.     TrieNode* pLoc = pRoot;  
  155.     while(pLoc && *str)  
  156.     {  
  157.         index = *str - 'a';//如果区分大小写,可以扩展  
  158.   
  159.         if(index < 0 || index > MaxBranchNum)//不是一个单词,不执行插入  
  160.         {  
  161.             return;  
  162.         }  
  163.   
  164.         pLoc = pLoc->nextBranch[index];  
  165.         str++;  
  166.     }  
  167.     if (pLoc)//条件成立,找到该单词  
  168.     {  
  169.         Print(pLoc);  
  170.     }  
  171. }  
  172.   
  173. /*按照字典顺序输出以pRoot为根的所有的单词*/  
  174. void Trie::Print(TrieNode* pRoot)  
  175. {  
  176.     if (NULL == pRoot)  
  177.     {  
  178.         return;  
  179.     }  
  180.     //输出单词  
  181.     if (NULL != pRoot->word)  
  182.     {  
  183.         cout<<pRoot->word<<" "<<pRoot->count<<endl;  
  184.     }  
  185.     //递归处理分支  
  186.     for (int i = 0;i < MaxBranchNum;i++)  
  187.     {  
  188.         Print(pRoot->nextBranch[i]);  
  189.     }  
  190. }  
  191.   
  192. /*销毁trie树*/  
  193. void Trie::Destory(TrieNode* pRoot)  
  194. {  
  195.     if (NULL == pRoot)  
  196.     {  
  197.         return;  
  198.     }  
  199.     for (int i = 0;i < MaxBranchNum;i++)  
  200.     {  
  201.         Destory(pRoot->nextBranch[i]);  
  202.     }  
  203.     //销毁单词占得空间  
  204.     if (NULL != pRoot->word)  
  205.     {  
  206.         delete []pRoot->word;     
  207.         pRoot->word = NULL;  
  208.     }  
  209.     delete pRoot;//销毁结点  
  210.     pRoot = NULL;  
  211. }  
  212.   
  213. int main()  
  214. {  
  215.     Trie t;  
  216.     string str;  
  217.     int count = -1;  
  218.     ifstream in("word.txt");  
  219.     //把单词输入字典树  
  220.     while(in >> str)  
  221.     {  
  222.         transform(str.begin(),str.end(),str.begin(),tolower);//大写变小写  
  223.         t.Insert(str.c_str());  
  224.     }  
  225.     //查找  
  226.     bool isFind = t.Search("the",count);  
  227.     if (isFind)  
  228.     {  
  229.         cout<<"存在the,出现次数:"<<count<<endl;  
  230.     }  
  231.     else  
  232.     {  
  233.         cout<<"不存在the!"<<endl;  
  234.     }  
  235.     //输出  
  236.     t.PrintALL();  
  237.     //删除  
  238.     bool isDel = t.Remove("the");  
  239.     if (isDel)  
  240.     {  
  241.         cout<<"删除成功!"<<endl;  
  242.     }  
  243.     else  
  244.     {  
  245.         cout<<"删除失败!"<<endl;  
  246.     }  
  247.     //输出以w开头的单词  
  248.     t.PrintPre("w");  
  249.     cout<<endl;  
  250.     system("pause");  
  251. }  
原创粉丝点击