尝试在Javascript中创建一个"trie"。无法弄清楚为什么我的方法没有正确添加子项



这是我创建的"constructor"函数和"inset"方法。。。

function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
let node = new Trie(null);
for(let character of string) {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
}
node = node.children[character];
}
node.endOfWord = true;
};

这是我创建的测试用例。。。

let trie = new Trie;
trie.insert('hello');
console.log(trie)

控制台日志的输出是…

Trie { value: undefined, endOfWord: false, children: {} }

根据我对"insert"函数的输入,我期待。。。

Trie { value: 'h', endOfWord: false, children: {value: 'e', endOfWord: false, children: {value: 'l', endOfWord: false, children: {value: 'l', endOfWord: false, children: {value: 'o', endOfWord: false, children: {}}}}} }

有什么线索或提示可以说明为什么没有正确添加孩子?

谢谢你抽出时间!

您需要在您所在的实例上使用子实例,而不是您创建的新实例。

因此,当您执行let node = new Trie(null);时,您正在创建一个新实例。您正在向其中添加子实例,而不是已创建的当前实例。

function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
let node = this;
for(let character of string) {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
}
node = node.children[character];
}
node.endOfWord = true;
};

let trie = new Trie;
trie.insert('hello');
console.log(trie)

您只是在创建一个新的Trie节点并将所有属性分配给它。您没有在任何地方使用它。

您将insert函数中的node视为调用它的对象,并且应该将所有属性分配为子级:

let node = this;

您可以直接使用this,但为了简单起见,我只将当前对象分配给node

function Trie(value) {
this.value = value;
this.endOfWord = false;
this.children = {};
}
Trie.prototype.insert = function(string) {
const node = this;
string.split("").forEach((character, index) => {
if (node.children[character] === undefined) {
node.children[character] = new Trie(character);
if (index === string.length - 1)
node.children[character].endOfWord = true;
}
});
};
let trie = new Trie();
trie.insert("hello");
console.log(trie);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新