Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda