Intento obtener los resultados de depthFirstTraverselfor con un árbol de búsqueda binario. Pero me sale una salida de Blanco.
Así que tengo esto:
class BST { constructor(value) { this.left = null; this.right = null; this.value = value; } insert(value) { if (value <= this.value) { if (!this.left) this.left = new BST(value); else this.left.insert(value); } else if (value > this.value) { if (!this.right) this.right = new BST(value); else { this.right.insert(value); } } } depthFirstTraversel = (iteratorFunc) => { if (this.left) this.left.depthFirstTraversel(iteratorFunc); if (this.right) this.right.depthFirstTraversel(iteratorFunc); }; } function log(value) { console.log(value); } const bst = new BST(50); bst.insert(30); bst.insert(70); bst.insert(100); bst.insert(60); bst.insert(59); bst.insert(20); bst.insert(45); bst.insert(35); bst.insert(85); bst.insert(105); bst.insert(10); bst.depthFirstTraversel(log);Entonces, lo que espero es un orden ascendente de los números: 10 20 30..etc
Pero obtengo una página de Blanco en las herramientas de desarrollo de Google Chrome
Su depthFirstTraversel no intenta generar nada, todo lo que hace es atravesar. Sigue pasando la función de log como un parámetro, por alguna razón, pero nunca la llama.
Aquí hay una versión corregida (eliminé pasar la función de registro como parámetro, porque solo se puede llamar directamente).
class BST { constructor(value) { this.left = null; this.right = null; this.value = value; } insert(value) { if (value <= this.value) { if (!this.left) this.left = new BST(value); else this.left.insert(value); } else if (value > this.value) { if (!this.right) this.right = new BST(value); else { this.right.insert(value); } } } depthFirstTraversel = () => { if (this.left) this.left.depthFirstTraversel(); log(this.value); if (this.right) this.right.depthFirstTraversel(); }; } function log(value) { console.log(value); } const bst = new BST(50); bst.insert(30); bst.insert(70); bst.insert(100); bst.insert(60); bst.insert(59); bst.insert(20); bst.insert(45); bst.insert(35); bst.insert(85); bst.insert(105); bst.insert(10); bst.depthFirstTraversel(log);