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

154
Visualizações
Tengo problemas para encontrar la altura de mi primer árbol de búsqueda binaria en JS

Aquí está mi función de constructor, así como mi método 'agregar' ...

 function BinarySearchTree(value) { this.value = value; this.right = null; this.left = null; } BinarySearchTree.prototype.add = function(value) { if (value < this.value) { if (this.left) this.left.add(value); else this.left = new BinarySearchTree(value); } if (value > this.value) { if (this.right) this.right.add(value); else this.right = new BinarySearchTree(value); } };

Aquí está el método 'getNodeHeight' que estoy tratando de hacer...

 BinarySearchTree.prototype.getNodeHeight = function(node) { if (node.value === null) { return -1; } return Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right)) + 1; }

Y aquí están los casos de prueba que estoy ejecutando...

 binarySearchTree = new BinarySearchTree(5); binarySearchTree.left = new BinarySearchTree(3); binarySearchTree.left.left = new BinarySearchTree(1); binarySearchTree.getNodeHeight(this);

Cada vez que registro el último en la consola, aparece "No se pueden leer las propiedades de undefined (leyendo 'valor')". Creo que puedo estar usando la palabra clave 'esto' incorrectamente... ¡pero he intentado jugar con ella y no puedo resolverlo!

Cualquier consejo, truco o ayuda sería muy apreciado... ¡Gracias por su tiempo!

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Hay 2 problemas, uno que señaló @Austin con respecto a la verificación de si el valor de entrada es nulo.

El otro problema es que no hay un valor predeterminado para getNodeHeight . Para esto, asumo que espera que el comportamiento predeterminado encuentre la altura de todo el árbol. Pasar this a getNodeHeight es pasar en el contexto donde está creando BinarySearchTree, no la instancia.

 function BinarySearchTree(value) { this.value = value; this.right = null; this.left = null; } BinarySearchTree.prototype.add = function(value) { if (value < this.value) { if (this.left) this.left.add(value); else this.left = new BinarySearchTree(value); } if (value > this.value) { if (this.right) this.right.add(value); else this.right = new BinarySearchTree(value); } }; BinarySearchTree.prototype.getNodeHeight = function(node = this) { if (node === null) { return -1; } return Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right)) + 1; } const binarySearchTree = new BinarySearchTree(5); binarySearchTree.left = new BinarySearchTree(3); binarySearchTree.left.left = new BinarySearchTree(1); console.log(binarySearchTree.getNodeHeight());

about 4 years ago · Santiago Trujillo Relatório

0

El problema está en la primera línea de su función getNodeHeight cuando se llama en node.right (que es null ). null no tiene una propiedad de value . El mismo error ocurrirá si evalúa

 null.value

Solucione esto cambiando

 if (node.value === null) ...

a

 if (!node) ...

En una investigación más profunda, el uso de la palabra clave this en binarySearchTree.getNodeHeight(this) probablemente devuelva una referencia a su objeto Window en lugar de binarySearchTree . Intente llamar al método a través de

 BinarySearchTree.prototype.getNodeHeight(binarySearchTree)

¡Buena suerte!

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