Árbol Binario de Búsqueda
Visualizador interactivo de BST con inserción, eliminación y recorridos.
Acerca de esta herramienta
Un árbol binario de búsqueda (ABB) mantiene sus claves ordenadas: todas las claves del subárbol izquierdo de un nodo son menores que él y todas las del subárbol derecho, mayores. Esa única regla hace que buscar, insertar y borrar cuesten un tiempo proporcional a la altura del árbol, y que un recorrido en orden devuelva las claves ordenadas.
Este laboratorio anima cada operación paso a paso. Verás qué comparación envía la búsqueda a la izquierda o a la derecha, dónde se engancha una clave nueva, cómo se resuelven los tres casos de borrado y en qué orden visitan los nodos los recorridos en preorden, en orden, en postorden y por niveles.
Cómo usar: Árbol Binario de Búsqueda
- Escribe un número y elige Insertar, Buscar o Borrar. La animación arranca sola; puedes pausarla y usar los botones de paso para avanzar o retroceder.
- Fíjate en el nodo resaltado y en la línea de estado: cada paso indica qué comparación se hizo y por qué el camino giró a la izquierda o a la derecha.
- Lanza un recorrido para ver cómo se construye el orden de visita bajo el árbol.
- Inserta claves en orden (1, 2, 3, 4, …) para ver cómo el árbol degenera en una lista enlazada, y compáralo con el laboratorio del árbol AVL.
Ejemplos
Camino de búsqueda
Árbol construido con 50, 30, 70, 20, 40, 60, 80 — buscar 60
50 → derecha → 70 → izquierda → 60 (encontrado en 3 comparaciones)
Borrar un nodo con dos hijos
Borrar 50 del árbol anterior
50 se sustituye por su sucesor en orden, 60, y luego se elimina 60 del subárbol derecho
Usar el predecesor en orden (la mayor clave de la izquierda) es igual de válido.
Recorridos
El mismo árbol
En orden: 20 30 40 50 60 70 80 · Preorden: 50 30 20 40 70 60 80 · Por niveles: 50 30 70 20 40 60 80
Implementación en cinco lenguajes
El mismo algoritmo en Python, JavaScript, Java, Go y C++. Cada programa está completo y se puede ejecutar; los comentarios indican lo que imprime.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)
return root # duplicates are ignored
def search(root, key):
while root is not None and root.key != key:
root = root.left if key < root.key else root.right
return root is not None
def delete(root, key):
if root is None:
return None
if key < root.key:
root.left = delete(root.left, key)
elif key > root.key:
root.right = delete(root.right, key)
else:
if root.left is None:
return root.right
if root.right is None:
return root.left
# Two children: copy the in-order successor, then delete it.
succ = root.right
while succ.left is not None:
succ = succ.left
root.key = succ.key
root.right = delete(root.right, succ.key)
return root
def inorder(root, out):
if root is not None:
inorder(root.left, out)
out.append(root.key)
inorder(root.right, out)
return out
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(inorder(root, [])) # [20, 30, 40, 50, 60, 70, 80]
print(search(root, 60)) # True
root = delete(root, 30)
print(inorder(root, [])) # [20, 40, 50, 60, 70, 80] class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
function insert(root, key) {
if (root === null) return new Node(key);
if (key < root.key) root.left = insert(root.left, key);
else if (key > root.key) root.right = insert(root.right, key);
return root; // duplicates are ignored
}
function search(root, key) {
while (root !== null && root.key !== key) {
root = key < root.key ? root.left : root.right;
}
return root !== null;
}
function remove(root, key) {
if (root === null) return null;
if (key < root.key) root.left = remove(root.left, key);
else if (key > root.key) root.right = remove(root.right, key);
else {
if (root.left === null) return root.right;
if (root.right === null) return root.left;
// Two children: copy the in-order successor, then delete it.
let succ = root.right;
while (succ.left !== null) succ = succ.left;
root.key = succ.key;
root.right = remove(root.right, succ.key);
}
return root;
}
function inorder(root, out = []) {
if (root !== null) {
inorder(root.left, out);
out.push(root.key);
inorder(root.right, out);
}
return out;
}
let root = null;
for (const k of [50, 30, 70, 20, 40, 60, 80]) root = insert(root, k);
console.log(inorder(root).join(", ")); // 20, 30, 40, 50, 60, 70, 80
console.log(search(root, 60)); // true
root = remove(root, 30);
console.log(inorder(root).join(", ")); // 20, 40, 50, 60, 70, 80 import java.util.ArrayList;
import java.util.List;
public class Main {
static class Node {
int key;
Node left, right;
Node(int key) { this.key = key; }
}
static Node insert(Node root, int key) {
if (root == null) return new Node(key);
if (key < root.key) root.left = insert(root.left, key);
else if (key > root.key) root.right = insert(root.right, key);
return root; // duplicates are ignored
}
static boolean search(Node root, int key) {
while (root != null && root.key != key) {
root = key < root.key ? root.left : root.right;
}
return root != null;
}
static Node delete(Node root, int key) {
if (root == null) return null;
if (key < root.key) root.left = delete(root.left, key);
else if (key > root.key) root.right = delete(root.right, key);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// Two children: copy the in-order successor, then delete it.
Node succ = root.right;
while (succ.left != null) succ = succ.left;
root.key = succ.key;
root.right = delete(root.right, succ.key);
}
return root;
}
static void inorder(Node root, List<Integer> out) {
if (root == null) return;
inorder(root.left, out);
out.add(root.key);
inorder(root.right, out);
}
public static void main(String[] args) {
Node root = null;
for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) root = insert(root, k);
List<Integer> keys = new ArrayList<>();
inorder(root, keys);
System.out.println(keys); // [20, 30, 40, 50, 60, 70, 80]
System.out.println(search(root, 60)); // true
root = delete(root, 30);
keys.clear();
inorder(root, keys);
System.out.println(keys); // [20, 40, 50, 60, 70, 80]
}
} package main
import "fmt"
type Node struct {
Key int
Left, Right *Node
}
func insert(root *Node, key int) *Node {
if root == nil {
return &Node{Key: key}
}
if key < root.Key {
root.Left = insert(root.Left, key)
} else if key > root.Key {
root.Right = insert(root.Right, key)
}
return root // duplicates are ignored
}
func search(root *Node, key int) bool {
for root != nil && root.Key != key {
if key < root.Key {
root = root.Left
} else {
root = root.Right
}
}
return root != nil
}
func remove(root *Node, key int) *Node {
if root == nil {
return nil
}
switch {
case key < root.Key:
root.Left = remove(root.Left, key)
case key > root.Key:
root.Right = remove(root.Right, key)
default:
if root.Left == nil {
return root.Right
}
if root.Right == nil {
return root.Left
}
// Two children: copy the in-order successor, then delete it.
succ := root.Right
for succ.Left != nil {
succ = succ.Left
}
root.Key = succ.Key
root.Right = remove(root.Right, succ.Key)
}
return root
}
func inorder(root *Node, out []int) []int {
if root == nil {
return out
}
out = inorder(root.Left, out)
out = append(out, root.Key)
return inorder(root.Right, out)
}
func main() {
var root *Node
for _, k := range []int{50, 30, 70, 20, 40, 60, 80} {
root = insert(root, k)
}
fmt.Println(inorder(root, nil)) // [20 30 40 50 60 70 80]
fmt.Println(search(root, 60)) // true
root = remove(root, 30)
fmt.Println(inorder(root, nil)) // [20 40 50 60 70 80]
} #include <iostream>
#include <memory>
#include <vector>
struct Node {
int key;
std::unique_ptr<Node> left, right;
explicit Node(int k) : key(k) {}
};
void insert(std::unique_ptr<Node>& root, int key) {
if (!root) { root = std::make_unique<Node>(key); return; }
if (key < root->key) insert(root->left, key);
else if (key > root->key) insert(root->right, key);
// duplicates are ignored
}
bool search(const Node* root, int key) {
while (root && root->key != key) {
root = key < root->key ? root->left.get() : root->right.get();
}
return root != nullptr;
}
void remove(std::unique_ptr<Node>& root, int key) {
if (!root) return;
if (key < root->key) remove(root->left, key);
else if (key > root->key) remove(root->right, key);
else if (!root->left) root = std::move(root->right);
else if (!root->right) root = std::move(root->left);
else {
// Two children: copy the in-order successor, then delete it.
Node* succ = root->right.get();
while (succ->left) succ = succ->left.get();
root->key = succ->key;
remove(root->right, succ->key);
}
}
void inorder(const Node* root, std::vector<int>& out) {
if (!root) return;
inorder(root->left.get(), out);
out.push_back(root->key);
inorder(root->right.get(), out);
}
void print(const std::unique_ptr<Node>& root) {
std::vector<int> keys;
inorder(root.get(), keys);
for (int k : keys) std::cout << k << ' ';
std::cout << '\n';
}
int main() {
std::unique_ptr<Node> root;
for (int k : {50, 30, 70, 20, 40, 60, 80}) insert(root, k);
print(root); // 20 30 40 50 60 70 80
std::cout << std::boolalpha << search(root.get(), 60) << '\n'; // true
remove(root, 30);
print(root); // 20 40 50 60 70 80
} Practica en LeetCode
Problemas clásicos que usan este algoritmo, ideales para después de explorar el laboratorio. Los enlaces abren LeetCode (en inglés).
Los tres casos de borrado
- Hoja: simplemente se elimina.
- Un hijo: se sustituye el nodo por su único hijo.
- Dos hijos: se copia en el nodo su sucesor en orden (la menor clave del subárbol derecho) y luego se borra el sucesor, que tiene como mucho un hijo.
Por qué importa la altura
Todas las operaciones siguen un único camino de la raíz a una hoja, así que cuestan O(h). Con un orden de inserción aleatorio la altura esperada ronda 2,99·log₂ n, pero una entrada ordenada da h = n y todas las operaciones se vuelven lineales. Los árboles autoequilibrados, como los AVL y los rojinegros, añaden rotaciones para mantener h = O(log n).
Preguntas frecuentes
Respuestas a tus dudas sobre el funcionamiento y la seguridad de los datos.
¿Cómo se tratan las claves duplicadas?
Este laboratorio ignora una clave que ya existe. Las implementaciones reales rechazan los duplicados, guardan un contador en el nodo o envían siempre las claves iguales al mismo lado.
¿Qué recorrido debo usar?
En orden para obtener una salida ordenada, preorden para copiar o serializar un árbol, postorden para liberar o evaluar los hijos antes que los padres (por ejemplo, en árboles de expresiones) y por niveles para procesar en anchura.
¿Un ABB es lo mismo que un montículo binario?
No. Un montículo solo garantiza que los padres son mayores (o menores) que sus hijos y no permite buscar de forma eficiente. Un ABB ordena los subárboles izquierdo y derecho y admite consultas ordenadas.
¿Mis datos están seguros con esta herramienta?
Totalmente seguros. Todo el procesamiento se ejecuta de forma local en tu navegador sin enviar información a ningún servidor.
Herramientas relacionadas
Árbol binario autoequilibrado con rotaciones LL, RR, LR y RL animadas.
Montículo max/min interactivo con vista dual de matriz y árbol.
Compare ordenamiento burbuja, selección, inserción, rápido, mezcla y montículo.
Proyectos destacados tech-fun.net
Explora más herramientas de IA y productividad
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.