字典树(Trie)是一种树形数据结构,常用于存储一个动态字符串集合或关联数组,其中键通常是字符串。与二叉搜索树不同,字典树的路径不表示存储在树中的值,但键与树中存储的数据相关联。一个节点的所有子节点通常都与该节点的字符相同。
定义字典树节点:
class TrieNode {
constructor() {
this.children = {}; // 存储子节点
this.isEndOfWord = false; // 标记当前节点是否是一个完整单词的结尾
}
}
定义字典树及其操作:
class Trie {
constructor() {
this.root = new TrieNode();
}
// 插入一个新的单词
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}
// 搜索一个单词是否存在
search(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
return false;
}
node = node.children[char];
}
return node.isEndOfWord;
}
// 检查给定的前缀是否存在
startsWith(prefix) {
let node = this.root;
for (let char of prefix) {
if (!node.children[char]) {
return false;
}
node = node.children[char];
}
return true;
}
}
使用示例:
const trie = new Trie();
trie.insert("apple");
console.log(trie.search("apple")); // true
console.log(trie.search("app")); // false
console.log(trie.startsWith("app")); // true
trie.insert("app");
console.log(trie.search("app")); // true