1. 程式人生 > >Trie樹的實現

Trie樹的實現

在電腦科學中,trie,又稱字首樹或字典樹,是一種有序樹,用於儲存關聯陣列,其中的鍵通常是字串。與二叉查詢樹不同,鍵不是直接儲存在節點中,而是由節點在樹中的位置決定。一個節點的所有子孫都有相同的字首,也就是這個節點對應的字串,而根節點對應空字串。一般情況下,不是所有的節點都有對應的值,只有葉子節點和部分內部節點所對應的鍵才有相關的值。圖片來源維基百科由Booyabazooka (based on PNG image by Deco). Modifications by Superm401. - own work (based on PNG image by Deco),公有領域,https://commons.wikimedia.org/w/index.php?curid=1197221
Trie這個術語來自於retrieval。根據詞源學,trie的發明者Edward Fredkin把它讀作/ˈtriː/ “tree”。但是,其他作者把它讀作/ˈtraɪ/ “try”

應用

trie樹常用於搜尋提示。如當輸入一個網址,可以自動搜尋出可能的選擇。當沒有完全匹配的搜尋結果,可以返回字首最相似的可能。leetcode211—WordDictionary
以下java實現:

import java.util.TreeMap;
public class Trie {
    private class  Node{
        public  boolean isWord;
        public TreeMap<Character,Node> next;
        public Node(boolean isWord){
            this.isWord=isWord;
            next=new TreeMap<>();
        }
        public Node(){
            this
(false); } } private Node root; private int size; public Trie(){ root=new Node(); size=0; } public int getSize(){ return size; } public void add(String word){ Node cur=root; for(int i=0;i<word.length();i++){ char
c=word.charAt(i); if(cur.next.get(c)==null){ cur.next.put(c,new Node()); } cur=cur.next.get(c); } if(!cur.isWord){ cur.isWord=true; size++; } } public boolean contains(String word){ Node cur=root; for(int i=0;i<word.length();i++){ char c=word.charAt(i); if(cur.next.get(c)==null){ return false; } cur=cur.next.get(c); } return cur.isWord; } public boolean isPrefix(String prefix){ Node cur=root; for(int i=0;i<prefix.length();i++){ char c=prefix.charAt(i); if(cur.next.get(c)==null){ return false; } } return true; } }