Trie查询树

trie树的特点:

                       拿内存换取时间,查询效率高

一、结点结构

public class TreeNode {

	char data;//节点数据
	boolean isEnd;//是否是结束
	LinkedList<TreeNode>childList;//子节点
	int count;//计数;
	
	public TreeNode(char c){
		this.data=c;
		isEnd=false;
		childList=new LinkedList<TreeNode>();
		count=0;
	}
	
	//子节点字符
	public TreeNode subNode(char c){
		if(childList!=null){
			for(TreeNode t:childList){
				if(t.data==c)return t;
			}
		}
		return null;
	}
}

 二、树的生成

 

public class TrieTree {

	//根节点根节点为空值
	private TreeNode root;
	
	
	//实例化的时候root的数据位空值
	public TrieTree(){
		root=new TreeNode(' ');
	}
	
	public void insertNode(String word){
		if(searchNode(word))return;
		
		 TreeNode current = root;  
		 
		         for(int i = 0; i < word.length(); i++){  
		             TreeNode child = current.subNode(word.charAt(i));  
		             if(child != null){   
		                 current = child;  
		             } else {  
		            	 current.childList.add(new TreeNode(word.charAt(i)));  
		                 current = current.subNode(word.charAt(i));  
		            }  
		            current.count++;  
		        }   
		        // Set isEnd to indicate end of the word  
		         current.isEnd = true;  
	}
	
	//搜索
	//由于他的第一个字符是否存在于root的子节点中然后顺藤
	public boolean searchNode(String word){
		TreeNode tn=root;
		for(int i=0;i<word.length();i++){
			if(tn.subNode(word.charAt(i))==null){
				return false;
			}else{
				tn=tn.subNode(word.charAt(i));
			}
		}
		return tn.isEnd;
	}
	}

 

 

    原文作者:Trie树
    原文地址: https://blog.csdn.net/iteye_4062/article/details/82535669
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞