我正在尝试在javascript中实现Trie数据结构。在仅打印包含trie中所有单词的数组的print函数内部,我还有另一个函数搜索,该函数搜索trie中的所有单词并将其推入数组。搜索功能两个参数'node'和'str'均具有默认值。当我在不传递任何参数的情况下调用该函数时,尽管该节点具有默认值且未定义,但仍会发生错误。
this.print = function(){
let words = new Array();
let search = function(node = this.root, string = new String()){
if(node.keys.size != 0){
if(node.isEnd() === true){
words.push(string);
}
for (let letter of node.keys.keys()){
search(node.keys.get(letter), string.concat(letter));
};
}else{
(string.length > 0) ? words.push(string) : undefined;
return;
}
};
search();
return words.length > 0 ? words : null;
};
TypeError:节点未定义trie.js:44:16
search http://127.0.0.1:5500/trie.js:44
print http://127.0.0.1:5500/trie.js:56
<anonymous> http://127.0.0.1:5500/trie.js:
答案 0 :(得分:0)
尝试一下:
this.print = function(self=this){
let words = new Array();
let search = function(node = self.root, string = new String()){
if(node.keys.size != 0){
if(node.isEnd() === true){
words.push(string);
}
for (let letter of node.keys.keys()){
search(node.keys.get(letter), string.concat(letter));
};
}else{
(string.length > 0) ? words.push(string) : undefined;
return;
}
};
search();
return words.length > 0 ? words : null;
};