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!
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());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.valueSolucione 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!