Skip to main content

Prefix tree

Implementation 1​

// note: using a class is only necessary if you want to store data at each node.
// otherwise, you can implement a trie using only hash maps.
class TrieNode {
constructor() {
// you can store data at nodes if you wish
this.data = null;
this.children = new Map();
}
}

let buildTrie = (words) => {
let root = new TrieNode();
for (const word of words) {
let curr = root;
for (const c of word) {
if (!curr.children.has(c)) {
curr.children.set(c, new TrieNode());
}
curr = curr.children.get(c);
}

// at this point, you have a full word at curr
// you can perform more logic here to give curr an attribute if you want
}

return root;
};

Implementation 2​

var Trie = function () {
this.children = new Map();
this.isEndOfWord = false;
};

/**
* @param {string} word
* @return {void}
*/
Trie.prototype.insert = function (word) {
let node = this;
for (const w of word) {
if (!node.children.has(w)) {
node.children.set(w, new Trie());
}

node = node.children.get(w);
}

node.isEndOfWord = true;
};

/**
* @param {string} word
* @return {boolean}
*/
Trie.prototype.search = function (word) {
let node = this;
for (const w of word) {
if (!node.children.has(w)) {
return false;
}
node = node.children.get(w);
}
return node.isEndOfWord;
};

/**
* @param {string} prefix
* @return {boolean}
*/
Trie.prototype.startsWith = function (prefix) {
let node = this;
for (const p of prefix) {
if (!node.children.has(p)) {
return false;
}
node = node.children.get(p);
}
return true;
};

/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/

Example​

https://leetcode.com/problems/search-suggestions-system/description/

img.png

/**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
class TrieNode {
constructor() {
this.children = new Map();
this.suggestions = [];
}
}

var suggestedProducts = function (products, searchWord) {
let root = new TrieNode();
for (const product of products) {
let node = root;
for (const c of product) {
if (!node.children.has(c)) {
node.children.set(c, new TrieNode());
}
node = node.children.get(c);

node.suggestions.push(product);
node.suggestions.sort();
if (node.suggestions.length > 3) {
node.suggestions.pop();
}
}
}

let ans = [];
let node = root;
for (const c of searchWord) {
if (node.children.has(c)) {
node = node.children.get(c);
ans.push(node.suggestions);
} else {
node.children = new Map();
ans.push([]);
}
}

return ans;
};