trie树(字典树)java实现

public class Trie{
    private Node root;
 
    public Trie(){
        root = new Node(' '); 
    }
 
    public void insert(String word){
    	if(search(word) == true) return;
    	
        Node current = root; 
        for(int i = 0; i < word.length(); i++){
            Node child = current.subNode(word.charAt(i));
            if(child != null){ 
                current = child;
            } else {
                 current.childList.add(new Node(word.charAt(i)));
                 current = current.subNode(word.charAt(i));
            }
            current.count++;
        } 
        current.isEnd = true;
    }

/**
     *怎么判断单词是否存在?
     *被判断的单词的字母与根节点下的子节点的字母进行比较,直到匹配到两者最后一个字母相同,并且最后一个节点的isEnd标记为true
     */
    public boolean search(String word){
        Node current = root;
        
        for(int i = 0; i < word.length(); i++){    
            if(current.subNode(word.charAt(i)) == null)
                return false;
            else
                current = current.subNode(word.charAt(i));
        }
        if (current.isEnd == true) return true;
        else return false;
    }
    
    public void deleteWord(String word){
        if(search(word) == false) return;
    
        Node current = root;
        for(char c : word.toCharArray()) { 
            Node child = current.subNode(c);
            if(child.count == 1) {
                current.childList.remove(child);
                return;
            } else {
                child.count--;
                current = child;
            }
        }
        current.isEnd = false;
    }
public static void main(String[] args) {
        Trie trie = new Trie();
        //trie.insert("ball");
        trie.insert("balls");
        trie.deleteWord("balls");
        trie.insert("sense");
    
        // testing deletion
        System.out.println(trie.search("balls"));
        System.out.println(trie.search("ba"));
        trie.deleteWord("balls");
        System.out.println(trie.search("balls"));
        System.out.println(trie.search("ball"));
    }
}

class Node {
    char content; // 节点包含的内容
    boolean isEnd; // 是否在该节点行成过一个单词
    int count;  // 统计该节点的字符被几个单词共享
    LinkedList<Node> childList; // 子节点的集合
  
    //初始化
    public Node(char c){
        childList = new LinkedList<Node>();
        isEnd = false;
        content = c;
        count = 0;
    }
  
    //查找子节点中是否有内容为x的子节点,有则返回该子节点,否则返回空
    public Node subNode(char c){
        if(childList != null){
            for(Node eachChild : childList){
                if(eachChild.content == c){
                     return eachChild;
                }
        	}
        }
        return null;
   }
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/u012572955/article/details/51331318
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞