0

// corre depth-first (en recorrido "in-order") cuando depthFirstForEach() es ejecutado sin ninguna opcion o con la opcion "in-order

// corre depth-first (en recorrido "pre-order") cuando depthFirstForEach() es ejecutado con la opcion "pre-order"

// corre depth-first (en recorrido "post-order" cuando depthFirstForEach() es ejecutado con la opcion "post-order

BinarySearchTree.prototype.inOrderTraversal = function(fn) {
  if (!this.left && !this.right) return fn(this.value) 
  if(!!this.left) this.left.inOrderTraversal(fn)
  fn(this.value) // print parent node after all its left nodes returned 
  if(!!this.right) this.right.inOrderTraversal(fn)
}

BinarySearchTree.prototype.preOrderTraversal = function(fn) {
  fn(this.value) // print parent node
  if(!!this.left) this.left.preOrderTraversal(fn) 
  if(!!this.right) this.right.preOrderTraversal(fn) 
}

BinarySearchTree.prototype.postOrderTraversal = function(fn) {
  if(!!this.left) this.left.preOrderTraversal(fn)
  if(!!this.right) this.right.preOrderTraversal(fn)
  fn(this.value) 
}                                                               

1 respuesta 1

0

Solo necesitarías agregar un método y comparar los valores de una opción pasada por el método y suponiendo que la función que utilizas como callback en cada uno de los métodos con los que recorres el árbol está definida

function testFn(value) {
    console.log(value)
}

BinarySearchTree.prototype.depthFirstForEach = function(option) {
    if (!option) {
        this.inOrderTraversal(testFn)
    }

    if (option === 'pre-order') {
        this.preOrderTraversal(testFn)
    }

    if (option === 'post-order') {
        this.postOrderTraversal(testFn);
    }
}

En caso que necesites pasar la función callback como argumento lo puedes añadir en la definición de la función depthFirstForEach

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.