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

98
Visualizações
Trouble finding the height of my first NON Binary Tree in JS

Here is the constructor function as well as the 'add' method...

function Tree(value) {
  this.value = value;
  this.children = [];
}


Tree.prototype.add = function(...value) {
  if (Array.isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      let node = new Tree;
      node.value = value[i];
      this.children[this.children.length] = node;
    }
    return;
  }
  let node = new Tree;
  node.value = value;
  this.children[this.children.length] = node;
};

Here is the 'height' method I am working on...

Tree.prototype.height = function() {
  let height = 0;
  if (this.children != null) {
    if (this.children.length == 0) {
      return height;
    } else {
      for (let i = 0; i < this.children.length; i++) {
        height = Math.max(height, this.height(this.children[i]));
      }
      return depth + 1;
  } 
    return height;
  }
};

I am unsure of why I am getting "RangeError: Maximum call stack size exceeded" because the method should return height if the children array length is 0.

Here are the test cases I am using...

tree = new Tree();
tree.add(5);
tree.add(8);
var son = tree.children[0];
son.add(1);
son.add(4);
var daughter = tree.children[0];
daughter.add(10);
var grandson = son.children[1];
grandson.add(3);
grandson.height() //should return 1
tree.height() //should return 

Any tips on how to fix my infinite loop will be greatly appreciated. Thank you for your time!

about 4 years ago · Santiago Trujillo
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