Trie 樹



原博客地址:http://blog.csdn.net/nash_/article/details/8227610

Trie樹(又叫字典樹,前綴樹,單詞查找樹,鍵樹)是一種樹形數據結構,直接來看圖:


我們來看看Trie樹的特點:根節點爲空值,剩下每一個節點保存一個字母。知道這些就夠了!

我們再來看看這棵樹能幹什麼?如果從根節點遍歷到某一個節點把路徑節點的值連在一起就構成了一個字符串,利用這個特點很容易想到這棵樹的第一個功能能幫我們查找某一個單詞是否在樹中(需要在每一個節點設置一個標誌,表示從根節點到此節點是否構成一個單詞);如果該單詞存在,我們可以利用它實現第二個功能:去除重複單詞;同樣如果該詞存,在我們還可以看出它的第三個功能:統計單詞頻率;因爲這是一個樹形結構我們利用這個特點很容易看出它的第四個功能能幫我們查找N個單詞的最長公共前綴;如果我們按順序遍歷輸出整棵樹,發現它的第五個功能:對字符串排序


這棵樹創建看起來比較容易,就有一個問題需要我們考慮:父節點如何保存孩子節點? 主要有兩種方式供大家參考:

1.因爲是英文字符,我們可以用Node[26]來保存孩子節點(如果是數字我們可以用Node[10]),這種方式最快,但是並不是所有節點都會有很多孩子,所以這種方式浪費的空間太多

2.用一個鏈表根據需要動態添加節點。這樣我們就可以省下不小的空間,但是缺點是搜索的時候需要遍歷這個鏈表,增加了時間複雜度。


下面我用數組保存孩子節點的方式實現的trie樹:

  1. class TrieNode{//結點類   
  2.       
  3.     private static final int  NUMBER = 26;  
  4.     private char _value;  
  5.     private boolean _isWord;//從根節點到這個節點存不存在一個單詞   
  6.     TrieNode[] _children = new TrieNode[NUMBER];//子結點集合   
  7.       
  8.     public TrieNode(char c) {  
  9.         this.setValue(c);  
  10.     }  
  11.     public char getValue() {  
  12.         return _value;  
  13.     }  
  14.     public void setValue(char _value) {  
  15.         this._value = _value;  
  16.     }  
  17.     public boolean isWord() {  
  18.         return _isWord;  
  19.     }  
  20.     public void setIsWord(boolean _isWord) {  
  21.         this._isWord = _isWord;  
  22.     }  
  23.       
  24.   
  25. }  
  26.   
  27. public class TrieTree {  
  28.       
  29.     static String[] _words = {"add","am","good","the","think"};//待插入單詞   
  30.   
  31.     private boolean searchWord(TrieNode _root, String _word) {  
  32.       
  33.         if(null == _root || null == _word || "".equals(_word))  
  34.             return false;  
  35.         char[] cs = _word.toCharArray();//將字符串轉化爲字符數組   
  36.         for(int i = 0; i < cs.length; i++){  
  37.               
  38.             int index;  
  39.             if(cs[i] >= 'A' && cs[i] <= 'Z'){  
  40.                 index = cs[i]-'A';  
  41.             }  
  42.             else if(cs[i] >= 'a' && cs[i] <= 'z')   
  43.                 index = cs[i] - 'a';  
  44.             else  
  45.                 return false;  
  46.               
  47.             TrieNode child_node = _root._children[index];  
  48.                   
  49.             if(null != child_node){//找到相同字符   
  50.                 if(child_node.isWord())//如果找到該單詞   
  51.                     return true;  
  52.             }                 
  53.               
  54.             if(null == child_node)//如果在i層沒找到相同字符       
  55.                 return false;  
  56.             _root = child_node;//重設根節點   
  57.               
  58.               
  59.         }  
  60.         return false;  
  61.     }  
  62.   
  63.   
  64.     private void insertIntoTree(TrieNode _root, String _word) {//插入一個單詞   
  65.           
  66.         if(null == _root || null == _word || "".equals(_word))  
  67.             return;  
  68.         char[] cs = _word.toCharArray();//將字符串轉化爲字符數組   
  69.         for(int i = 0; i < cs.length; i++){  
  70.               
  71.             int index;//對應的索引值   
  72.             if(cs[i] >= 'A' && cs[i] <= 'Z'){  
  73.                 index = cs[i]-'A';  
  74.             }  
  75.             else if(cs[i] >= 'a' && cs[i] <= 'z')   
  76.                 index = cs[i] - 'a';  
  77.             else  
  78.                 return;  
  79.               
  80.             TrieNode child_node = _root._children[index];  
  81.             if(null == child_node){//如果沒找到   
  82.                 TrieNode new_node = new TrieNode(cs[i]);//創建新節點   
  83.                 if(i == cs.length-1)//如果遍歷到該單詞最後一個字符   
  84.                     new_node.setIsWord(true);//把該單詞存在樹中   
  85.                 _root._children[index] = new_node;//連接該節點   
  86.                 _root = new_node;  
  87.                   
  88.             }else  
  89.                 _root = child_node;//更新樹根   
  90.               
  91.               
  92.         }  
  93.     }  
  94.   
  95.     private void printTree(TrieNode _root,char[] _word,int index) {  
  96.           
  97.         if(_root == null)  
  98.             return;  
  99.         if(_root.isWord()){//如果根節點到此節點構成一個單詞則輸出   
  100.             for(char c : _word){  
  101.                 if(c != ' ')  
  102.                     System.out.print(c);  
  103.             }  
  104.                   
  105.             System.out.println();  
  106.         }  
  107.               
  108.         for(TrieNode node : _root._children){//遍歷樹根孩子節點   
  109.             if(node != null){//回溯法遍歷該樹   
  110.                 _word[index++] = node.getValue();  
  111.                 printTree(node,_word,index);  
  112.                 _word[index] = ' ';  
  113.                 index--;  
  114.             }  
  115.         }  
  116.               
  117.     }  
  118.     public static void main(String[] args){  
  119.         TrieTree _tree = new TrieTree();//創建一棵樹   
  120.         TrieNode _root = new TrieNode(' ');//創建根節點   
  121.         for(String word : _words)//插入單詞   
  122.             _tree.insertIntoTree(_root,word);  
  123.         char[] _word = new char[20];  
  124.         _tree.printTree(_root,_word,0);//打印樹中單詞   
  125.         boolean status = _tree.searchWord(_root,"think");//查詢樹中是否存在某單詞   
  126.         System.out.println(status);  
  127.     }  
  128. }  
  1. class TrieNode{//結點類  
  2.       
  3.     private static final int  NUMBER = 26;  
  4.     private char _value;  
  5.     private boolean _isWord;//從根節點到這個節點存不存在一個單詞  
  6.     TrieNode[] _children = new TrieNode[NUMBER];//子結點集合  
  7.       
  8.     public TrieNode(char c) {  
  9.         this.setValue(c);  
  10.     }  
  11.     public char getValue() {  
  12.         return _value;  
  13.     }  
  14.     public void setValue(char _value) {  
  15.         this._value = _value;  
  16.     }  
  17.     public boolean isWord() {  
  18.         return _isWord;  
  19.     }  
  20.     public void setIsWord(boolean _isWord) {  
  21.         this._isWord = _isWord;  
  22.     }  
  23.       
  24.   
  25. }  
  26.   
  27. public class TrieTree {  
  28.       
  29.     static String[] _words = {"add","am","good","the","think"};//待插入單詞  
  30.   
  31.     private boolean searchWord(TrieNode _root, String _word) {  
  32.       
  33.         if(null == _root || null == _word || "".equals(_word))  
  34.             return false;  
  35.         char[] cs = _word.toCharArray();//將字符串轉化爲字符數組  
  36.         for(int i = 0; i < cs.length; i++){  
  37.               
  38.             int index;  
  39.             if(cs[i] >= 'A' && cs[i] <= 'Z'){  
  40.                 index = cs[i]-'A';  
  41.             }  
  42.             else if(cs[i] >= 'a' && cs[i] <= 'z')   
  43.                 index = cs[i] - 'a';  
  44.             else  
  45.                 return false;  
  46.               
  47.             TrieNode child_node = _root._children[index];  
  48.                   
  49.             if(null != child_node){//找到相同字符  
  50.                 if(child_node.isWord())//如果找到該單詞  
  51.                     return true;  
  52.             }                 
  53.               
  54.             if(null == child_node)//如果在i層沒找到相同字符      
  55.                 return false;  
  56.             _root = child_node;//重設根節點  
  57.               
  58.               
  59.         }  
  60.         return false;  
  61.     }  
  62.   
  63.   
  64.     private void insertIntoTree(TrieNode _root, String _word) {//插入一個單詞  
  65.           
  66.         if(null == _root || null == _word || "".equals(_word))  
  67.             return;  
  68.         char[] cs = _word.toCharArray();//將字符串轉化爲字符數組  
  69.         for(int i = 0; i < cs.length; i++){  
  70.               
  71.             int index;//對應的索引值  
  72.             if(cs[i] >= 'A' && cs[i] <= 'Z'){  
  73.                 index = cs[i]-'A';  
  74.             }  
  75.             else if(cs[i] >= 'a' && cs[i] <= 'z')   
  76.                 index = cs[i] - 'a';  
  77.             else  
  78.                 return;  
  79.               
  80.             TrieNode child_node = _root._children[index];  
  81.             if(null == child_node){//如果沒找到  
  82.                 TrieNode new_node = new TrieNode(cs[i]);//創建新節點  
  83.                 if(i == cs.length-1)//如果遍歷到該單詞最後一個字符  
  84.                     new_node.setIsWord(true);//把該單詞存在樹中  
  85.                 _root._children[index] = new_node;//連接該節點  
  86.                 _root = new_node;  
  87.                   
  88.             }else  
  89.                 _root = child_node;//更新樹根  
  90.               
  91.               
  92.         }  
  93.     }  
  94.   
  95.     private void printTree(TrieNode _root,char[] _word,int index) {  
  96.           
  97.         if(_root == null)  
  98.             return;  
  99.         if(_root.isWord()){//如果根節點到此節點構成一個單詞則輸出  
  100.             for(char c : _word){  
  101.                 if(c != ' ')  
  102.                     System.out.print(c);  
  103.             }  
  104.                   
  105.             System.out.println();  
  106.         }  
  107.               
  108.         for(TrieNode node : _root._children){//遍歷樹根孩子節點  
  109.             if(node != null){//回溯法遍歷該樹  
  110.                 _word[index++] = node.getValue();  
  111.                 printTree(node,_word,index);  
  112.                 _word[index] = ' ';  
  113.                 index--;  
  114.             }  
  115.         }  
  116.               
  117.     }  
  118.     public static void main(String[] args){  
  119.         TrieTree _tree = new TrieTree();//創建一棵樹  
  120.         TrieNode _root = new TrieNode(' ');//創建根節點  
  121.         for(String word : _words)//插入單詞  
  122.             _tree.insertIntoTree(_root,word);  
  123.         char[] _word = new char[20];  
  124.         _tree.printTree(_root,_word,0);//打印樹中單詞  
  125.         boolean status = _tree.searchWord(_root,"think");//查詢樹中是否存在某單詞  
  126.         System.out.println(status);  
  127.     }  
  128. }  
發佈了14 篇原創文章 · 獲贊 23 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章