Laboratorio interactivoSe ejecuta en tu navegador

Visualizador de Árbol AVL

Árbol binario autoequilibrado con rotaciones LL, RR, LR y RL animadas.

Velocidad:
Árbol AVL equilibrado. El número junto a cada nodo es su factor de balance (altura izq. − der.).
Casos de rotación:
100200300500600700800
Nodos: 7Altura: 3 desequilibrado (|bf| > 1)
Pseudocódigo
1insert(node, v):
2 BST-insert v below node
3 node.height = 1 + max(h(left), h(right))
4 bf = h(left) - h(right)
5 if bf > 1 and v < left.key: rotateRight (LL)
6 if bf < -1 and v > right.key: rotateLeft (RR)
7 if bf > 1: rotateLeft(left); rotateRight (LR)
8 if bf < -1: rotateRight(right); rotateLeft (RL)

Acerca de esta herramienta

Un árbol AVL es un árbol binario de búsqueda que se reequilibra solo. Cada nodo guarda su altura, y el factor de equilibrio (altura del subárbol izquierdo menos la del derecho) debe mantenerse entre −1 y +1. Cuando una inserción o un borrado saca a un nodo de ese rango, una o dos rotaciones lo restablecen, así que la altura nunca supera aproximadamente 1,44·log₂ n.

Este laboratorio muestra el factor de equilibrio de cada nodo, resalta el primer nodo desequilibrado al volver hacia la raíz y nombra el caso de rotación aplicado (LL, RR, LR o RL), para que veas exactamente por qué cambia la forma del árbol.

Cómo usar: Visualizador de Árbol AVL

  1. Inserta claves una a una o usa el ajuste predefinido que inserta una secuencia ordenada: la entrada que arruina un ABB normal.
  2. Observa cómo se actualizan los factores de equilibrio tras cada inserción. Un ±2 en rojo marca el nodo que necesita rotar.
  3. Sigue el paso de rotación: la línea de estado nombra el caso y los nodos implicados.
  4. Borra también claves: a diferencia de la inserción, un borrado puede provocar rotaciones en varios niveles camino de la raíz.

Ejemplos

Caso derecha-derecha

Entrada
Insertar 10, 20, 30
Resultado
El nodo 10 queda con equilibrio −2 → una rotación a la izquierda → 20 pasa a ser la raíz con hijos 10 y 30

Caso izquierda-derecha

Entrada
Insertar 30, 10, 20
Resultado
Rotación a la izquierda en 10 y luego a la derecha en 30 → raíz 20

Una entrada ordenada sigue siendo poco profunda

Entrada
Insertar 1 … 15 en orden
Resultado
Un árbol perfecto de altura 4 en lugar de una cadena de 15 nodos

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
        self.height = 1


def height(n):
    return n.height if n else 0


def update(n):
    n.height = 1 + max(height(n.left), height(n.right))


def balance(n):
    return height(n.left) - height(n.right)


def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    update(y)
    update(x)
    return x


def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    update(x)
    update(y)
    return y


def insert(node, key):
    if node is None:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
    else:
        return node
    update(node)
    b = balance(node)
    if b > 1 and key < node.left.key:      # LL
        return rotate_right(node)
    if b < -1 and key > node.right.key:    # RR
        return rotate_left(node)
    if b > 1:                              # LR
        node.left = rotate_left(node.left)
        return rotate_right(node)
    if b < -1:                             # RL
        node.right = rotate_right(node.right)
        return rotate_left(node)
    return node


def preorder(n, out):
    if n:
        out.append(n.key)
        preorder(n.left, out)
        preorder(n.right, out)
    return out


root = None
for k in [10, 20, 30, 40, 50, 25]:
    root = insert(root, k)
print(preorder(root, []))   # [30, 20, 10, 25, 40, 50]
print(root.height)          # 3
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
    this.height = 1;
  }
}

const height = (n) => (n ? n.height : 0);
const update = (n) => { n.height = 1 + Math.max(height(n.left), height(n.right)); };
const balance = (n) => height(n.left) - height(n.right);

function rotateRight(y) {
  const x = y.left;
  y.left = x.right;
  x.right = y;
  update(y);
  update(x);
  return x;
}

function rotateLeft(x) {
  const y = x.right;
  x.right = y.left;
  y.left = x;
  update(x);
  update(y);
  return y;
}

function insert(node, key) {
  if (node === null) return new Node(key);
  if (key < node.key) node.left = insert(node.left, key);
  else if (key > node.key) node.right = insert(node.right, key);
  else return node;

  update(node);
  const b = balance(node);
  if (b > 1 && key < node.left.key) return rotateRight(node); // LL
  if (b < -1 && key > node.right.key) return rotateLeft(node); // RR
  if (b > 1) { // LR
    node.left = rotateLeft(node.left);
    return rotateRight(node);
  }
  if (b < -1) { // RL
    node.right = rotateRight(node.right);
    return rotateLeft(node);
  }
  return node;
}

function preorder(n, out = []) {
  if (n) {
    out.push(n.key);
    preorder(n.left, out);
    preorder(n.right, out);
  }
  return out;
}

let root = null;
for (const k of [10, 20, 30, 40, 50, 25]) root = insert(root, k);
console.log(preorder(root).join(', ')); // 30, 20, 10, 25, 40, 50
console.log(root.height); // 3
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Node {
        int key, height = 1;
        Node left, right;
        Node(int key) { this.key = key; }
    }

    static int height(Node n) { return n == null ? 0 : n.height; }
    static void update(Node n) { n.height = 1 + Math.max(height(n.left), height(n.right)); }
    static int balance(Node n) { return height(n.left) - height(n.right); }

    static Node rotateRight(Node y) {
        Node x = y.left;
        y.left = x.right;
        x.right = y;
        update(y);
        update(x);
        return x;
    }

    static Node rotateLeft(Node x) {
        Node y = x.right;
        x.right = y.left;
        y.left = x;
        update(x);
        update(y);
        return y;
    }

    static Node insert(Node node, int key) {
        if (node == null) return new Node(key);
        if (key < node.key) node.left = insert(node.left, key);
        else if (key > node.key) node.right = insert(node.right, key);
        else return node;

        update(node);
        int b = balance(node);
        if (b > 1 && key < node.left.key) return rotateRight(node);   // LL
        if (b < -1 && key > node.right.key) return rotateLeft(node);  // RR
        if (b > 1) {                                                  // LR
            node.left = rotateLeft(node.left);
            return rotateRight(node);
        }
        if (b < -1) {                                                 // RL
            node.right = rotateRight(node.right);
            return rotateLeft(node);
        }
        return node;
    }

    static void preorder(Node n, List<Integer> out) {
        if (n == null) return;
        out.add(n.key);
        preorder(n.left, out);
        preorder(n.right, out);
    }

    public static void main(String[] args) {
        Node root = null;
        for (int k : new int[] {10, 20, 30, 40, 50, 25}) root = insert(root, k);
        List<Integer> keys = new ArrayList<>();
        preorder(root, keys);
        System.out.println(keys);         // [30, 20, 10, 25, 40, 50]
        System.out.println(root.height);  // 3
    }
}
package main

import "fmt"

type Node struct {
	Key, Height int
	Left, Right *Node
}

func height(n *Node) int {
	if n == nil {
		return 0
	}
	return n.Height
}

func update(n *Node) { n.Height = 1 + max(height(n.Left), height(n.Right)) }

func balance(n *Node) int { return height(n.Left) - height(n.Right) }

func rotateRight(y *Node) *Node {
	x := y.Left
	y.Left = x.Right
	x.Right = y
	update(y)
	update(x)
	return x
}

func rotateLeft(x *Node) *Node {
	y := x.Right
	x.Right = y.Left
	y.Left = x
	update(x)
	update(y)
	return y
}

func insert(node *Node, key int) *Node {
	if node == nil {
		return &Node{Key: key, Height: 1}
	}
	if key < node.Key {
		node.Left = insert(node.Left, key)
	} else if key > node.Key {
		node.Right = insert(node.Right, key)
	} else {
		return node
	}

	update(node)
	b := balance(node)
	switch {
	case b > 1 && key < node.Left.Key: // LL
		return rotateRight(node)
	case b < -1 && key > node.Right.Key: // RR
		return rotateLeft(node)
	case b > 1: // LR
		node.Left = rotateLeft(node.Left)
		return rotateRight(node)
	case b < -1: // RL
		node.Right = rotateRight(node.Right)
		return rotateLeft(node)
	}
	return node
}

func preorder(n *Node, out []int) []int {
	if n == nil {
		return out
	}
	out = append(out, n.Key)
	out = preorder(n.Left, out)
	return preorder(n.Right, out)
}

func main() {
	var root *Node
	for _, k := range []int{10, 20, 30, 40, 50, 25} {
		root = insert(root, k)
	}
	fmt.Println(preorder(root, nil)) // [30 20 10 25 40 50]
	fmt.Println(root.Height)         // 3
}
#include <algorithm>
#include <iostream>
#include <vector>

struct Node {
    int key, height = 1;
    Node *left = nullptr, *right = nullptr;
    explicit Node(int k) : key(k) {}
};

int height(Node* n) { return n ? n->height : 0; }
void update(Node* n) { n->height = 1 + std::max(height(n->left), height(n->right)); }
int balance(Node* n) { return height(n->left) - height(n->right); }

Node* rotateRight(Node* y) {
    Node* x = y->left;
    y->left = x->right;
    x->right = y;
    update(y);
    update(x);
    return x;
}

Node* rotateLeft(Node* x) {
    Node* y = x->right;
    x->right = y->left;
    y->left = x;
    update(x);
    update(y);
    return y;
}

Node* insert(Node* node, int key) {
    if (!node) return new Node(key);
    if (key < node->key) node->left = insert(node->left, key);
    else if (key > node->key) node->right = insert(node->right, key);
    else return node;

    update(node);
    int b = balance(node);
    if (b > 1 && key < node->left->key) return rotateRight(node);   // LL
    if (b < -1 && key > node->right->key) return rotateLeft(node);  // RR
    if (b > 1) {                                                    // LR
        node->left = rotateLeft(node->left);
        return rotateRight(node);
    }
    if (b < -1) {                                                   // RL
        node->right = rotateRight(node->right);
        return rotateLeft(node);
    }
    return node;
}

void preorder(Node* n, std::vector<int>& out) {
    if (!n) return;
    out.push_back(n->key);
    preorder(n->left, out);
    preorder(n->right, out);
}

void destroy(Node* n) {
    if (!n) return;
    destroy(n->left);
    destroy(n->right);
    delete n;
}

int main() {
    Node* root = nullptr;
    for (int k : {10, 20, 30, 40, 50, 25}) root = insert(root, k);
    std::vector<int> keys;
    preorder(root, keys);
    for (int k : keys) std::cout << k << ' ';   // 30 20 10 25 40 50
    std::cout << '\n' << root->height << '\n';  // 3
    destroy(root);
}

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).

Cómo elegir la rotación

  • LL (equilibrio +2, hijo izquierdo ≥ 0): una rotación a la derecha.
  • RR (equilibrio −2, hijo derecho ≤ 0): una rotación a la izquierda.
  • LR (equilibrio +2, hijo izquierdo < 0): rotar el hijo izquierdo a la izquierda y luego el nodo a la derecha.
  • RL (equilibrio −2, hijo derecho > 0): rotar el hijo derecho a la derecha y luego el nodo a la izquierda.

¿AVL o árbol rojinegro?

Los AVL están más estrictamente equilibrados, así que las búsquedas son algo más rápidas; los rojinegros toleran más desequilibrio y rotan menos al actualizar. Por eso muchas bibliotecas estándar (std::map en C++, TreeMap en Java) usan árboles rojinegros, mientras que algunos índices con mucha lectura prefieren AVL.

Preguntas frecuentes

Respuestas a tus dudas sobre el funcionamiento y la seguridad de los datos.

¿Cuántas rotaciones puede causar una inserción?

Como mucho una rotación simple o una doble. Después, el subárbol vuelve a tener la altura que tenía antes de la inserción, así que no hay que corregir nada por encima.

¿Y un borrado?

Un borrado puede acortar un subárbol, así que puede hacer falta rotar en cada nivel hasta la raíz: O(log n) en el peor caso.

¿Una rotación rompe el orden del árbol de búsqueda?

No. Una rotación solo cambia qué nodo es el padre; la secuencia en orden de las claves sigue siendo exactamente la misma.

¿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.