树的家族如下图所示:
堆是具有下列性质的完全二叉树:每个节点的值都小于等于其左右孩子节点值是小根堆;(大于等于则是大根堆)。
有些参考书将堆直接定义为序列,但是,从逻辑结构上讲,还是将堆定义为完全二叉树更好。虽然堆的典型实现方法是数组,但从逻辑的角度上讲,堆实际上是一种树结构。
Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种,典型应用是用于统计和排序大量相同的字符串,所以经常被搜索引擎系统用于文本词频统计。它的优点是: 利用字符串的公共前缀来减少查询时间,最大限度地减少无谓字符串的比较。
Trie的核心思想是空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
前缀树的三个基本性质:
查询复杂度:
单词查询场景:
208. 实现 Trie (前缀树)
class Trie {//根节点private Node root;public Trie() {root=new Node(false);}public void insert(String word) {Node cur=root;char[] charArray=word.toCharArray();for(char c:charArray){int index=c-'a';if(cur.childern[index]==null){cur.childern[index]=new Node(false);}cur=cur.childern[index];}cur.isEnd=true;}public boolean search(String word) {Node res=doSearch(word); return res!=null && res.isEnd;}public boolean startsWith(String prefix) {return doSearch(prefix)!=null; }public Node doSearch(String str){Node cur=root;char[] charArray=str.toCharArray();for(char c:charArray){int index=c-'a';if(cur.childern[index]==null){return null;}cur=cur.childern[index];}return cur; }public static class Node{//结束标记private boolean isEnd;//孩子节点private Node[] childern;public Node(boolean end){childern=new Node[26];isEnd=end;} }
}
class Trie {//根节点private Node root;public Trie() {root=new Node(false);}public void insert(String word) {Node cur=root;char[] charArray=word.toCharArray();for(char c:charArray){if(!cur.childern.containsKey(c)){cur.childern.put(c,new Node(false));}cur=cur.childern.get(c);}cur.isEnd=true;}public boolean search(String word) {Node res=doSearch(word); return res!=null && res.isEnd;}public boolean startsWith(String prefix) {return doSearch(prefix)!=null; }public Node doSearch(String str){Node cur=root;char[] charArray=str.toCharArray();for(char c:charArray){if(!cur.childern.containsKey(c)){return null;}cur=cur.childern.get(c);}return cur; }public static class Node{//结束标记private boolean isEnd;//孩子节点private Map childern;public Node(boolean end){childern=new HashMap<>();isEnd=end;} }
}
字典树刷题总结