Solución

@duron03·hace 4dTypeScript
solution.tsTypeScript
type node = {
        value: number,
        right: (node | null),
        left: (node | null)
};

class BST {
    constructor(private root: (node | null) = null, private numberOfElements: number = 0) {}

    public insert(num: number): void {
        let currNode: (node | null) = {
            value: num,
            right: null,
            left: null
        }
        if (this.getRoot() === null) {
            this.setRoot(currNode);
            this.updateNumberOfElements();
            return;
        }
        currNode = this.getRoot();
        let newNode: node = {
            value: num,
            right: null,
            left: null
        }
        while (currNode !== null) {
            if (currNode.value < num) {
                if (currNode.left === null) {
                    currNode.left = newNode;
                    this.updateNumberOfElements();
                    currNode = null;
                }
                else currNode = currNode.left;
            }
            else {
                if (currNode.right === null) {
                    currNode.right = newNode;
                    this.updateNumberOfElements();
                    currNode = null;
                }
                else currNode = currNode.right;
            }
        }
    }
    public search(num: number): boolean {
        if (this.getRoot === null || this.getElements() === 0) return false;

        let currNode: (node | null) = this.getRoot();
        while (currNode !== null) {
            if (currNode.value === num) {
                return true;
            }
            if (currNode.value < num) currNode = currNode.left;
            else currNode = currNode.right;
        }
        return false;
    }
    public getRoot(): (node | null) { return this.root; }
    private setRoot(node: node): void { this.root = node; }
    private updateNumberOfElements(): void { this.numberOfElements += 1; }
    public getElements(): number { return this.numberOfElements; }
};

function binarySearchTree(operations: [string, number][]): boolean[] {
  let bst = new BST();
    let arrRes: boolean[] = [];

    for (let i: number = 0; i < operations.length; i++) {
        let operation: string = operations[i][0];
        let value: number = operations[i][1];

        if (operation === "insert") bst.insert(value);
        else if (operation === "search") arrRes.push(bst.search(value));
    }
    return arrRes;
}

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

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.