简介
根据维基百科介绍:
在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
图示
实现
class TrieNode {
constructor() {
this.path = 0; // 记录每个字符经过该节点的次数;
this.end = 0; // 记录经过该节点的字符串个数;
this.next = new Array(26).fill(null); // 记录节点的子路径,26个英文字母有26条路径;初始为null;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(str) {
if (!str) return;
let node = this.root;
for(let i = 0, len = str.length; i < len; i++) {
let index = str[i].charCodeAt() - 'a'.charCodeAt();
if (!node.next[index]) {
node.next[index] = new TrieNode;
}
node.path += 1;
node = node.next[index];
}
node.end += 1;
}
search(str) {
if (!str) return;
let node = this.root;
for(let i = 0, len = str.length; i < len; i++) {
let index = str[i].charCodeAt() - 'a'.charCodeAt();
if (!node.next[index]) {
return 0;
}
node = node.next[index];
}
return node.end;
}
delete(str) {
if (!this.search(str)) return;
let node = this.root;
for(let i = 0, len = str.length; i < len; i++) {
let index = str[i].charCodeAt() - 'a'.charCodeAt();
if (--node.next[index].path === 0 ) {
node.next[index] = null;
}
node = node.next[index];
}
node.end -= 1;
}
}