A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

ADT – Arvore Binária de Pesquisa

Apresentações semelhantes


Apresentação em tema: "ADT – Arvore Binária de Pesquisa"— Transcrição da apresentação:

1 ADT – Arvore Binária de Pesquisa
ATAI

2 Árvore Binária de Pesquisa (Binary Search Tree)
Árvore binária de pesquisa (BST) é uma árvore binária especial (ordenada). A localização do nó é determinada pela chave (identificador único) do elemento. Uma árvore binária de pesquisa é uma árvore binária com as seguintes propriedades: a chave de qualquer nó é maior que todas as chaves da subárvore esquerda; a chave de qualquer nó é menor (ou igual) que todas as chaves da subárvore direita. Se a chave é uma cadeia de caracteres, então a cadeia de caracteres da esquerda deve ser lexicalmente menor que a cadeia de caracteres da direita.

3 Exemplo (a) dog cat fox lion pig rat tiger (b) pig cat dog fox lion

4 Definição Recursiva Uma BST é: vazia, ou Não vazia, neste caso possui:
Uma raiz que possui um elemento elem Um ligação à sub-árvores esquerda na qual (se não for vazia) todos os elementos são menores do que elem Um ligação à sub-árvores direita na qual (se não for vazia) todos os elementos são maiores do que elem

5 Procura numa BST 1. Por curr para a raiz da BST. 2. Repetir: se curr é null: Terminar com resposta não senão, se target é igual ao elemento na posição curr: Terminar com resposta curr se não, se target é menor do que elemento curr: curr passa a ser o seu filho esquerdo se não , se target é maior do que elemento curr: curr passa a ser o seu filho direito.

6 Procura numa BST (com sucesso)
To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr target

7 Procura numa BST (sem sucesso)
To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1. Set curr to the BST’s root. 2. Repeat: If curr is null, terminate with answer none Otherwise, if target is equal to curr’s element, terminate with answer curr Otherwise, if target is less than curr’s element, set curr to curr’s left child Otherwise, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger goat target

8 Inserir elemento numa BST
Ideia: Para iserir um novo elemento numa BST, processa como no método de procura. Se o elemento não estiver já presente, o método de procura vai terminar numa ligação nula. Substitua esta ligação nula por uma ligação para um nó (do tipo folha) que possui o elemento.

9 Remover elemento numa BST
1. Eliminar o elemento com as árvores esquerda e direita vazias (implica remoção do nó) 2. Eliminar o elemento com a árvores esquerda (ou direita) vazia (implica remoção do nó)

10 Remover elemento numa BST (cont.)
3. Eliminar o elemento com as árvores esquerda e direita não vazias Soluções: Substituir o valor do nó a eliminar com o valor do nó mais a direita na árvore esquerda do nó a eliminar (i.e. maior valor da árvore esquerda) Apagar o nó mais a direita. Substituir o valor do nó a eliminar com o valor do nó mais a esquerda na árvore direita do nó a eliminar (i.e. menor valor da árvore direita) Apagar o nó mais a esquerda.

11 Remover elemento numa BST (exemplos)

12 Remover elemento numa BST (exemplos)

13 Exemplo: Inserções Sucessivas
Animação (Inserir ‘lion’, ‘fox’, ‘rat’, ‘cat’, ‘pig’, ‘dog’, ‘tiger’): Após inserir ‘pig’: cat fox lion pig rat Após inserir ‘dog’: dog cat fox lion pig rat Após inserir ‘tiger’: dog cat fox lion pig rat tiger Após inserir ‘cat’: cat fox lion rat Após inserir ‘fox’: fox lion Após inserir ‘lion’: lion Inicio: Após inserir ‘rat’: fox lion rat

14 Exemplo: Inserções Sucessivas
Animação(Inserir ‘cat’, ‘dog’, ‘fox’, ‘lion’, ‘pig’, ‘rat’): Após inserir ‘pig’: dog cat fox lion pig Após inserir ‘rat’: dog cat fox lion pig rat Após inserir ‘lion’: dog cat fox lion Após inserir‘dog’: dog cat Inicio: Após inserir ‘cat’: cat Após inserir‘fox’: dog cat fox

15 Interface da àrvore Binária de Pesquisa (BinarySearchTree - BST)
public interface BinarySearchTree { public void insert(Comparable x ); //Insere o Elemento x public void remove(Comparable x ); //Remove o Elemento x public Comparable findMin( ); //Retorna o menor elemento public Comparable findMax( ); //Retorna o maior elemento public Position findKey(Comparable key ); //Retorna a posição do //elemento com a chave key public boolean isEmpty( ); //Retorna TRUE se está vazia public void printTreeIn(); //Imprime os Elementos em INORDER public void printTreePre(); //Elementos em PREORDER public void printTreePos(); //Elementos em POSORDER }

16 Implementação: versão iterativa

17 Classe nó do BST public class BSTNode implements Position{
protected Comparable element; protected BSTNode left, right; protected BSTNode (Comparable elem) { element = elem; left = null; right = null; } public Comparable element() { return element; } public void setElement (Comparable elem){ element = elem; …. BSTNode metodos gets e sets

18 Classe BST public class BST implements BinarySearchTree {
private BSTNode root; public BST () { // cria uma árvore vazia root = null; } }

19 Método de procura public Position findKey (Comparable target) { int direction = 0; BSTNode curr = root; for (;;) { if (curr == null) return null; direction = target.compareTo(curr.element()); if (direction == 0) return curr; else if (direction < 0) curr = curr.getLeft(); else curr = curr.getRight(); } }

20 Método inserir public void insert (Comparable elem) { int direction = 0; BSTNode parent = null, curr = root; for (;;) { if (curr == null) { BSTNode ins = new BSTNode(elem); if (root == null) root = ins; else if (direction < 0) parent.setLeft(ins); else parent.setRight(ins); return; } direction = elem.compareTo(curr.element()); if (direction == 0) return; parent = curr; if (direction < 0) curr = curr.getLeft(); else curr = curr.getRight(); } }

21 Eliminar um nó da árvore (versão menor dos maiores)

22 Método privado que retorna o elemento mais a esquerda da árvore
private Comparable getLeftmost () { BSTNode curr = this; while (curr.getLeft() != null) curr = curr.getLeft(); return curr.element(); }

23 Método privado que elimina o elemento mais a esquerda da árvore
private BSTNode deleteLeftmost () { if (this.left == null) return this.right; else { BSTNode parent = this, curr = this.getLeft(); while (curr.getLeft() != null) { parent = curr; curr = curr.getLeft(); } parent.setLeft(curr.getRight()); return this; } }

24 Eliminar um nó do topo da árvore
public BSTNode deleteTopmost () { if (this.left == null) return this.getRight();//não tem sub-árvore esquerda else if (this.right == null) return this.getLeft ();//não tem sub-árvore direita else { // nó tem dois filhos this.element = (this.getRight()).getLeftmost(); this.setRight((this.getRight()).deleteLeftmost()); return this; } }

25 Eliminar um nó da árvore
public void remove (Comparable elem) { int direction = 0; BSTNode parent = null, curr = root; for (;;) { if (curr == null) return; direction = elem.compareTo(curr.element()); if (direction == 0) { BSTNode del = curr.deleteTopmost();//eliminar o curr if (curr == root) root = del; else if (curr == parent.getLeft()) parent.setLeft(del); else parent.setRight(del); return; } parent = curr; if (direction < 0) curr = parent.getLeft(); else // direction > 0 curr = parent.getRight(); } }

26 Imprimir os elementos da árvore (in-order)
public static void printInOrder (BSTNode top) { // imprima em forma crescente // todos os elementos da árvore top if (top != null) { printInOrder(top.getLeft()); System.out.println(top.element()); printInOrder(top.getRight()); } }

27 Implementação: versão recursiva

28 Operação insert // Se o elemento existir não se insere
// Inserir elemento x na Árvore; // Se o elemento existir não se insere public void insert( Comparable x ) { root = insert( x, root ); } /* * Retorna o novo Nó */ private BinaryNode insert( Comparable x, BinaryNode t ) if( t == null ) t = new BSTNode( x, null, null ); else if( x.compareTo( t.element() ) < 0 ) t.setLeft (insert( x, t.getLeft() )); else if( x.compareTo( t.element() ) > 0 ) t.setRight (insert( x, t.getRight() )); else ;// Se houver duplicação não inserir o elemento return t;

29 Operação remove { if( t == null ) return t;
private BSTNode remove( Comparable x, BSTNode t ) { if( t == null ) return t; if( x.compareTo( t.element ) < 0 ) t.setLeft( remove( x, t.getLeft() ); else if( x.compareTo( t.element ) > 0 ) t.setRight( remove( x, t.getRight() ); else if( t.getLeft() != null && t.getRight() != null ) t.setElement(findMin( t.getRight ()).element); t.setRight (remove( t.element, t.right ); } else t = ( t.getLeft() != null ) ? t.getLeft() : t.getRight();

30 Operação que retorna o menor elemento da árvore
public Comparable findMin( ) { return element( findMin( root ) ); } private BSTNode findMin (BSTNode t ) if( t == null ) return null; else if( t.getLeft() == null ) return t; return findMin( t.getLeft() );


Carregar ppt "ADT – Arvore Binária de Pesquisa"

Apresentações semelhantes


Anúncios Google