java
package bst;
// Actualiza count
private static<E> void updateCount(Node<E> h) {
h.count = count(h.left) + count(h.right) + 1;
}
////////////////// Contagem de nós da árvore /////////////////////////
private static<E> int countR(Node<E> h) {
if (h == null)
return 0;
return countR(h.left) + countR(h.right) + 1;
}
public int count() { return countR(root); }
private static<E> int count(Node<E> h) {
if (h == null)
return 0;
return h.count;
}
////////////////// Altura da árvore /////////////////////////
private static<E> int height(Node<E> h) {
if (h == null)
return -1;
int u = height(h.left), v = height(h.right);
if (u > v)
return u+1;
else
return v+1;
}
public int height() { return height(root); }
if (less(e, parent.item))
parent.left = new Node<E>(e);
else
parent.right = new Node<E>(e);
// Actualiza count
updateCount(parent);
Página 3
BinarySearchTree.java
}
public void insert(E e) {
root = insertR(root, e);
//insertIterative(v);
}
////////////////// Rotação /////////////////////////
// Actualiza count
updateCount(y);
updateCount(aux);
return aux;
}
////////////////// Inserção na raiz /////////////////////////
private static<E extends Comparable<E>> Node<E> insertRootR(Node<E> h, E e)
{
if (h == null)
return new Node<E>(e);
if (less(e, h.item)) {
h.left = insertRootR(h.left, e);
h = rotRight(h);
}
else {
h.right = insertRootR(h.right, e);
h = rotLeft(h);
}
return h;
}
public void insertRoot(E e) {
root = insertRootR(root, e);
}
////////////////// Selecção /////////////////////////
private static<E> E selectR(Node<E> h, int k) {
if (h == null)
return null;
int t = count(h.left);
if (t > k)
return selectR(h.left, k);
if (t < k)
return selectR(h.right, k-t-1);
return h.item;
}
// Assume que índice k é válido
Página 4
BinarySearchTree.java
public E select(int k) {
return selectR(root, k);
}
////////////////// Partição /////////////////////////
private static<E> Node<E> partR(Node<E> h, int k) {
if (h == null)
return null;
int t = count(h.left);
if (t > k) {
h.left = partR(h.left, k);
h = rotRight(h);
}
if (t < k) {
h.right = partR(h.right, k-t-1);
h = rotLeft(h);
}
return h;
}
// Remoção
int rem = 5;
//int rem = 2;
//int rem = 12;
//int rem = 17;
bst.remove(rem);
// Remoção
System.out.println("Apos remocao de " + rem);
bst.print();
// Selecção
System.out.println("[Seleccao] k=0: " + bst.select(0));
System.out.println("[Seleccao] k=mediana: " +
bst.select(bst.count()/2));
/*
// Percurso
System.out.println("Percurso prefixo");
bst.traverse();
// Percurso em profundidade
System.out.println("Percurso em profundidade");
bst.depthFirst();
// Percurso em largura
System.out.println("Percurso em largura");
bst.breadthFirst();
*/
}
}
Página 6