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 =derecha;
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();