Underc0de

Programación Web => Front-end => Mensaje iniciado por: Adalher en Noviembre 16, 2020, 11:08:13 PM

Título: JavaScript - Árbol binario inmutable
Publicado por: Adalher en Noviembre 16, 2020, 11:08:13 PM
Hola a todos,

pensé en publicar algo que no se ve todos los días en JavaScript. Un árbol binario inmutable y ordenado al que se le puede agregar, eliminar, y mostrar datos.

Código (javascript) [Seleccionar]

class Vacio {
  constructor() {
    Object.freeze(this);
  }
  agregar(datos) {
    return new Nodo(datos, this, this);
  }
  mostrar() {
    console.log("vacio");
  }
  encontrar(_) {
    return this;
  }
  eliminar(_) {
    return this;
  }
  unir_ramas(izquierda, _) {
    return izquierda;
  }
}

class Nodo {
  constructor(datos, izquierda, derecha) {
    this.datos = datos;
    this.izquierda = izquierda;
    this.derecha =derechas;
    Object.freeze(this);
  }
  agregar(datos) {
    if (this.datos < datos) {
      return new Nodo(this.datos, this.izquierda.agregar(datos), this.derecha);
    } else if (this.datos > datos) {
      return new Nodo(this.datos, this.izquierda, this.derecha.agregar(datos));
    } else {
      return this;
    }
  }
  mostrar() {
    this.izquierda.mostrar();
    console.log(this.datos);
    this.derecha.mostrar();
  }
  encontrar(datos) {
    if (this.datos < datos) {
      return this.izquierda.encontrar(datos);
    } else if (this.datos > datos) {
      return this.derecha.encontrar(datos);
    } else {
      return this;
    }
  }
  eliminar(datos) {
    if (this.datos < datos) {
      return new Nodo(this.datos, this.izquierda.eliminar(datos), this.derecha);
    } else if (this.datos > datos) {
      return new Nodo(this.datos, this.izquierda, this.derecha.eliminar(datos));
    } else {
      if (this.izquierda === null) {
        return this.derecha;
      } else if (this.derecha === null) {
        return this.izquierda;
      } else {
        return this.derecha.unir_ramas(this.izquierda);
      }
    }
  }
  unir_ramas(izquierda) {
    return new Nodo(this.datos, this.izquierda.unir_ramas(izquierda), this.derecha);
  }
}

const arr = [10, 1, 9, 2, 8, 3, 7, 4, 6, 5].reduce((a, e) => { return a.agregar(e) }, new Vacio());

arr.mostrar();

console.log("\n\n");

(arr.encontrar(8)).mostrar();

console.log("\n\n");

const ans = [2, 4, 6, 8, 10, 1, 3, 5, 10, 10].reduce((a, e) => { return a.eliminar(e) }, arr);

ans.mostrar();


Es solo algo con lo que estaba jugando mientras me familiarizaba con JavaScript. Lo sé, no es muy práctico en JavaScript pero necesito practicar en algo.


Saludos