Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!