Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Rbolavl 120514103918 Phpapp01
Rbolavl 120514103918 Phpapp01
Descripcin
Factor de equilibrio
OPERACIONES
Insercin
Extraccin
CDIGO EN JAVA
Class AvlNode
/**
*
* @author Diego
*/
public class AVLNode {
public
public
public
public
Comparable dato;
AVLNode izquierdo;
AVLNode derecho;
int height;
// Constructors
public AVLNode(Comparable dato) {
this(dato, null, null);
}
public AVLNode(Comparable dato, AVLNode izq, AVLNode der) {
this.dato = dato;
this.izquierdo = izq;
this.derecho = der;
height = 0;
// altura predeterminada
}
}
Class AvlTree
public class AVLTree {
private AVLNode root;
public void insert(Comparable x) {
root = insertar(x, root);
}
/*
* x es una instancia de una clase que implementa Comparable
*/
private AVLNode insertar(Comparable x, AVLNode t) {
if (t == null) {
t = new AVLNode(x, null, null);
} else if (x.compareTo(t.dato) < 0) {
t.izquierdo = insertar(x, t.izquierdo);
if (height(t.izquierdo) - height(t.derecho) == 2) {
if (x.compareTo(t.izquierdo.dato) < 0) {
t = rotacionHijoIzquierdo(t); /* Caso 1 */
} else {
t = rotacionDobleHijoIzquierda(t); /* Caso 2 */
}
}
} else if (x.compareTo(t.dato) > 0) {
t.derecho = insertar(x, t.derecho);
if (height(t.derecho) - height(t.izquierdo) == 2) {
if (x.compareTo(t.derecho.dato) > 0) {
t = rotacionHijoDerecho(t); /* Caso 4 */
} else {
t = rotacionDobleHijoDerecho(t); /* Caso 3 */
}
}
} else
; // Duplicado; no hago nada
t.height = max(height(t.izquierdo), height(t.derecho)) + 1;
return t;
}
/*
/*
* Obtiene la altura del arbol AVL
*/
public int calcularAltura() {
return calcularAltura(root);
}
private int calcularAltura(AVLNode actual) {
if (actual == null) {
return -1;
} else {
return 1 + Math.max(calcularAltura(actual.izquierdo),
calcularAltura(actual.derecho));
}
}
if (cola[i] != null) {
System.out.print("[" + cola[i].dato + "]");
cont++;
}
if (ultimaPosicion == i && cantidad ==
Math.pow(2, --nivel)) {
if (cantidad == 1) {
System.out.print(" Cantidad de nodos: " +
cont + " (raiz)");
} else {
System.out.print(" Cantidad de nodos: " +
cont);
}
cont = 0;
cantidad *= 2;
ultimaPosicion += (int) Math.pow(2, ++nivel);
}
}
}
}
Class EjecutableAvlTree
/**
*
* @author Diego
*/
public class EjecutableAVLTree {
arbolAVL.insert(elemento1);
arbolAVL.insert(elemento2);
arbolAVL.insert(elemento3);
arbolAVL.insert(elemento4);
arbolAVL.insert(elemento5);
arbolAVL.insert(elemento6);
arbolAVL.insert(elemento7);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
AVLTree arbolAVL = new AVLTree();
arbolAVL.insert(elemento8);
arbolAVL.insert(elemento9);
arbolAVL.insert(elemento10);
arbolAVL.imprimirPorNiveles();
int altura = arbolAVL.calcularAltura() + 1;
Integer
Integer
Integer
Integer
Integer
Integer
Integer
Integer
Integer
Integer
System.out.println("\n");
System.out.println(altura + " altura del arbol");
System.out.println("\n");
arbolAVL.imprimirPorAltura();
}
}