Trie 樹(轉自 http://hi.baidu.com/luyade1987/item/7c1977f5e9015cdf6225d224)

來源:互聯網
上載者:User
Trie樹|字典樹的簡介及實現Trie,又稱字典樹、單詞尋找樹,是一種樹形結構,用於儲存大量的字串。它的優點是:利用字串的公用首碼來節約儲存空間。相對來說,Trie樹是一種比較簡單的資料結構.理解起來比較簡單,正所謂簡單的東西也得付出代價.故Trie樹也有它的缺點,Trie樹的記憶體消耗非常大.當然,或許用左兒子右兄弟的方法建樹的話,可能會好點.其基本性質可以歸納為:1. 根節點不包含字元,除根節點外每一個節點都只包含一個字元。 2. 從根節點到某一節點,路徑上經過的字元串連起來,為該節點對應的字串。 3. 每個節點的所有子節點包含的字元都不相同。其基本操作有:尋找 插入和刪除,當然刪除操作比較少見.我在這裡只是實現了對整個樹的刪除操作,至於單個word的刪除操作也很簡單.搜尋字典項目的方法為:(1) 從根結點開始一次搜尋;(2) 取得要尋找關鍵詞的第一個字母,並根據該字母選擇對應的子樹並轉到該子樹繼續進行檢索;(3) 在相應的子樹上,取得要尋找關鍵詞的第二個字母,並進一步選擇對應的子樹進行檢索。(4) 迭代過程……(5) 在某個結點處,關鍵詞的所有字母已被取出,則讀取附在該結點上的資訊,即完成尋找。其他動作類似處理./*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;} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.