【发布时间】:2021-04-13 12:02:30
【问题描述】:
我是数据结构的初学者。我刚刚开始学习它。我正在尝试使用 trie 数据结构创建一个家庭结构。我在这里指的是 github 上的文档: https://gist.github.com/tpae/72e1c54471e88b689f85ad2b3940a8f0#file-trie-js-L44
这是一些代码。
function TrieNode(key) {
// the "key" value will be the character in sequence
this.key = key;
// we keep a reference to parent
this.parent = null;
// we have hash of children
this.children = {};
// check to see if the node is at the end
this.end = false;
}
// -----------------------------------------
// we implement Trie with just a simple root with null value.
function Trie() {
this.root = new TrieNode(null);
}
// inserts a word into the trie.
// time complexity: O(k), k = word length
Trie.prototype.insert = function(word) {
var node = this.root; // we start at the root ????
// for every character in the word
for(var i = 0; i < word.length; i++) {
// check to see if character node exists in children.
if (!node.children[word[i]]) {
// if it doesn't exist, we then create it.
node.children[word[i]] = new TrieNode(word[i]);
// we also assign the parent to the child node.
node.children[word[i]].parent = node;
}
// proceed to the next depth in the trie.
node = node.children[word[i]];
// finally, we check to see if it's the last word.
if (i == word.length-1) {
// if it is, we set the end flag to true.
node.end = true;
}
}
};
我的疑问是在插入节点时,我们如何遍历单词并创建一个节点:
node.children[word[i]]
这对我来说是无法理解的。还有如何在函数 TrieNode 中声明键、父、子?它们是否被视为在创建对象时初始化的全局变量?为什么在其他函数中声明了 root 以及它是如何工作的? 附言我必须像这样插入树:
var familyHead = {
name: 'Chit',
gender:'Male',
grandfather:'',
grandmother:'',
father:'Shan',
mother:'Anga',
wife:'Amba',
children : [
{
name: 'Chit',
gender:'Male',
grandfather:'',
grandmother:'',
father:'Shan',
mother:'Anga',
wife:'Amba',
children :[]
}]
} ...继续
【问题讨论】:
-
node.children[word[i]]有什么不明白的地方?如果word是类似HELLO的字符串,那么word[i]是该字符串中的一个字母,例如H。children是一个 JavaScript 对象,所以我们讨论的是该对象的属性,其键为H,即TrieNode。你了解this.children = {}的作用吗?你追那么多吗?您能具体说明您在这里做什么或不了解什么吗? -
感谢@Wyck 在这里的输入。雅现在我明白了。我的另一个疑问是,我们通过调用 insert 函数直接插入了“hello”、“apple”等词或任何字符串。我想了解插入方法内部发生了什么?意味着孩子对象存储和父母是什么?另外,你能看到我的家谱结构吗?如何插入这样的树,然后根据输入作为名称获取关系?
-
当心:the difference between tree and trie 您可能只需要一个 tree 来存储 family tree。 trie 用于通过重用这些单词的公共前缀子串的表示来有效地存储单词集合。例如,单词
grandfather和grandmother将只存储一次常用字母g,r,a,n,d。将单词father和mother的表示存储在 trie 中单词grand的表示下方。 -
明白了!你能告诉我函数 TrieNode(key) {} 吗?在这种情况下如何直接声明父、子对象?它们是全局变量吗?为什么首先不使用 'var' 或 'let' 关键字声明然后使用它? @Wyck
-
它们不是全局变量。它们是对象的属性。我写了一个完整的答案。如果您的问题只是您不了解构造函数、属性和变量的工作原理,请原谅我的冗长。如果是这种情况,那么就该语言的特定方面提出一个更有针对性的问题,这会给您带来麻烦,范围大大缩小。
标签: javascript node.js trie family-tree