-
Notifications
You must be signed in to change notification settings - Fork 116
Open
Description
字典树(Trie)数,又称单词查找树或键数,典型应用是用于统计和排序大量的字符串,经常被搜索引擎用于文本词频统计。
优点:最大限度地减少无谓的字符串比较,查询效率比哈希表高
- 结点本身不存在完整单词
- 从根节点到某结点,路径上经过的字符连接起来,为该结点对应的字符串
- 每个结点的所有子结点路径代码的字符都不相同
Trie数实现如下
class TrieNode {
private final int R = 26;
private TrieNode[] links;
private boolean isEnd;
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch) {
return links[ch - 'a'] != null;
}
public TrieNode get(char ch) {
return links[ch - 'a'];
}
public void put(char ch, TrieNode node) {
links[ch - 'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return isEnd;
}
}
class Trie {
public TrieNode root;
/**
* Initialize your data structure here.
*/
public Trie() {
root = new TrieNode();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!node.containsKey(ch)) {
node.put(ch, new TrieNode());
}
node = node.get(ch);
}
node.setEnd();
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
private TrieNode searchPrefix(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (node.containsKey(ch)) {
node = node.get(ch);
} else {
return null;
}
}
return node;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
}
二叉搜索树(有序二叉树、排序二叉树)
- 左子树上所有结点的值均小于它的根结点的值
- 右子树上所有结点的值均大于它的根结点的值
以此类推:左、右子区为分别为二叉查找树
AVL树(平衡二叉树)
- 平衡因子:左子树的高度减去右子树的高度{-1,0,1}
- 通过旋转操作来进行平衡(四种旋转操作)
缺点:节点需要存储额外信息、且调整次数频繁
红黑树(近似平衡的二叉搜索树)
能确保任何一个结点的左右子树的高度差小于两倍
- 每个结点要么是红,要么是黑
- 根结点是黑色的
- 每个叶子结点(NIL节点,空节点)是黑色
- 不能有相邻接的两个红色节点
- 从任一节点到起=其每个叶子的所有路径都包含相同数据的黑色节点
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels