Solución

@rjnunezc_e48c1c70
·30/3/2026TypeScript
solution.tsTypeScript
class Node {

  constructor(
    public value: number,
    public left: Node | null = null,
    public right: Node | null = null
  ) {}

}

class Tree {

  public root: Node | null;

  constructor () {
    this.root = null;
  }

  insert (value: number): void {
    const newNode = new Node(value);

    if (!this.root) {
      this.root = newNode;
    } else {
      let currentNode = this.root;
      while (true) {
        if (value >= currentNode.value) {
          if (!currentNode.right) {
            currentNode.right = newNode;
            return;
          }
          currentNode = currentNode.right;
        } else {
          if (!currentNode.left) {
            currentNode.left = newNode;
            return;
          }
          currentNode = currentNode.left;
        }
      }
    }
  }

  search (target: number): boolean {
    let currentNode = this.root;

    if (!currentNode) return false;

    while (currentNode) {
      if (target === currentNode.value) {
        return true;
      } else if (target >= currentNode.value) {
        currentNode = currentNode.right;
      } else {
        currentNode = currentNode.left;
      }
    }

    return false;
  }

}

function binarySearchTree(operations: [string, number][]): boolean[] {
  const searchOperations: boolean[] = [];
  
  const tree = new Tree();

  for (const operation of operations) {

    const [op, value] = operation;

    switch (op) {
      case "insert":
        tree.insert(value);
        break;
      case "search":
        const searchOperationResult = tree.search(value);
        searchOperations.push(searchOperationResult);
        break;
    }

  }

  return searchOperations;
}

// No modificar: necesario para evaluar el resultado.
export { binarySearchTree };
0respuestas
Respuestas
0

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.
Markdown