Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Trying to create a 'trie' in Javascript. Can't figure out why my method isn't adding the children correctly

Here is the 'constructor' function as well as the 'inset' method I created...

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;
};

Here is the test case I created...

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

the output for the console log is...

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

based on my input into the 'insert' function I was expecting...

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: {}}}}} }

Any clues or tips as to why this isn't adding the children correctly?

Thanks for your time!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to use the children on the instance you are on, not the new instance you created.

So when you do let node = new Trie(null); you are creating a new instance. You are adding the children to that, not the current instance you already created.

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

You are just creating a new Trie node and assign all property to it. You are not using it anywhere.

You are considering node inside the insert function as the object which is calling it and you should assign all the property as a children:

let node = this;

You can directly use this but for simplicity I've just assign the current object to the 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; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda