Files
freeCodeCamp/curriculum/challenges/espanol/10-coding-interview-prep/data-structures/use-breadth-first-search-in-a-binary-search-tree.md
2022-12-12 20:56:32 +05:30

6.5 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d8258367417b2b2512c7f Usa la busqueda Breadth First en una busqueda de arbol binario 1 301718 use-breadth-first-search-in-a-binary-search-tree

--description--

Aquí introduciremos otro método de arbol transversal: la busqueda breadth-first. En contraste al método de busqueda depth-first del último reto, la busqueda breadth-first explora todos los nodos en un nivel dado dentro del arbol antes de continuar con el siguiente nivel. Normalmente, las colas son utilizadas como estructuras de datos de apoyo en el diseño de los algoritmos de busqueda breadth-first.

En este método, empezamos agregando el nodo raíz a la cola. Luego empezamos un ciclo donde obtenemos el primer elemento de la cola, lo agregamos a un nuevo array, y luego inspeccionamos ambos sub-arboles hijos. Si sus hijos no son nulos, entonces ambos serán encolados. Este proceso continua hasta que la cola está vacía.

--instructions--

Creamos un método de búsqueda de primera-amplitud en nuestro árbol llamado levelOrder. Este método debería devolver un arreglo conteniendo los valores de todos los nodos del árbol, explorados en la forma primera-amplitud. Asegurate de devolver los valores en el arreglo, no los nodos por sí mismos. Un nivel debería ser atravesado de izquierda a derecha. Siguiente, escriberemos un método similar llamado reverseLevelOrder cual efectuara la misma búsqueda pero en la dirección inversa (derecha a izquierda) en cada nivel.

--hints--

La estructura de datos BinarySearchTree debería existir.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    }
    return typeof test == 'object';
  })()
);

El árbol de búsqueda binaria debería tener un método llamado levelOrder.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    return typeof test.levelOrder == 'function';
  })()
);

El árbol de búsqueda binaria debería tener un método llamado reverseLevelOrder.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    return typeof test.reverseLevelOrder == 'function';
  })()
);

El método levelOrder debería devolver un arreglo de valores de nodo del árbol explorados en level order.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    if (typeof test.levelOrder !== 'function') {
      return false;
    }
    test.add(7);
    test.add(1);
    test.add(9);
    test.add(0);
    test.add(3);
    test.add(8);
    test.add(10);
    test.add(2);
    test.add(5);
    test.add(4);
    test.add(6);
    return test.levelOrder().join('') == '719038102546';
  })()
);

El método reverseLevelOrder debería devolver un arreglo de valores de nodo de árbol explorados en reverse level order.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    if (typeof test.reverseLevelOrder !== 'function') {
      return false;
    }
    test.add(7);
    test.add(1);
    test.add(9);
    test.add(0);
    test.add(3);
    test.add(8);
    test.add(10);
    test.add(2);
    test.add(5);
    test.add(4);
    test.add(6);
    return test.reverseLevelOrder().join('') == '791108305264';
  })()
);

El método levelOrder debería devolver null para un árbol vacío.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    if (typeof test.levelOrder !== 'function') {
      return false;
    }
    return test.levelOrder() == null;
  })()
);

El método reverseLevelOrder debería devolver null para un árbol vacio.

assert(
  (function () {
    var test = false;
    if (typeof BinarySearchTree !== 'undefined') {
      test = new BinarySearchTree();
    } else {
      return false;
    }
    if (typeof test.reverseLevelOrder !== 'function') {
      return false;
    }
    return test.reverseLevelOrder() == null;
  })()
);

--seed--

--after-user-code--

BinarySearchTree.prototype = Object.assign(
  BinarySearchTree.prototype,
  {
    add: function(value) {
      function searchTree(node) {
        if (value < node.value) {
          if (node.left == null) {
            node.left = new Node(value);
            return;
          } else if (node.left != null) {
            return searchTree(node.left);
          }
        } else if (value > node.value) {
          if (node.right == null) {
            node.right = new Node(value);
            return;
          } else if (node.right != null) {
            return searchTree(node.right);
          }
        } else {
          return null;
        }
      }
      var node = this.root;
      if (node == null) {
        this.root = new Node(value);
        return;
      } else {
        return searchTree(node);
      }
    }
  }
);

--seed-contents--

var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
  this.value = value;
  this.left = null;
  this.right = null;
}
function BinarySearchTree() {
  this.root = null;
  // Only change code below this line

  // Only change code above this line
}

--solutions--

var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
  this.value = value;
  this.left = null;
  this.right = null;
}
function BinarySearchTree() {
  this.root = null;
  // Only change code below this line
  this.levelOrder = (root = this.root) => {
    if(!root) return null;
    let queue = [root];
    let results = [];
    while(queue.length > 0) {
      let node = queue.shift();
      results.push(node.value);
      if(node.left) queue.push(node.left);
      if(node.right) queue.push(node.right);
    }
    return results;
  }

  this.reverseLevelOrder = (root = this.root) => {
    if(!root) return null;
    let queue = [root];
    let results = [] ;
    while ( queue.length > 0) {
      let node = queue.shift();
      results.push(node.value);
      if(node.right) queue.push(node.right);
      if(node.left ) queue.push(node.left);
    }
    return results;
  }
  // Only change code above this line
}