ADT – Arvore Binária de Pesquisa

Slides:



Advertisements
Apresentações semelhantes
Visualização do OpenGL
Advertisements

TADs Vector, Lista e Sequência
Programação em Java Prof. Maurício Braga
Motivação para listas duplamente encadeadas e circulares
14/10/09 Uma animação possui: Início; Passo; Fim; 1.
Estruturas de Dados Árvores Binárias
Interação entre objetos
TAD Deque ATAI.
Orientação a Objetos: Encapsulamento e Classificação
Java: Pacotes e Modificadores de Visibilidade
Percurso não recursivo e impressão em árvores binárias Drozdek.
Série de Exercícios.
Árvores.
Pilhas e Filas.
Classificação. 2 Métodos de Classificação Os métodos de classificação podem ser dos tipos: Classificação interna – quando toda a coleção de itens a classificar.
Árvores B Implementação pelos FrameWork Bruno Preiss.
Listas Ordenadas e Listas Classificadas. 2 Sumário Fundamentos Listas Ordenadas Listas Classificadas.
Árvores.
Árvores de Busca. 2 Uma árvore que suporta eficientes operações de busca, inclusão e exclusão é chamada de árvore de busca. A árvore é usada para armazenar.
Listas Encadeadas Circulares Listas Duplamente Encadeadas
Filas circulares.
DIAGRAMA DE ATIVIDADES
Listas Encadeadas Circulares Listas Duplamente Encadeadas
André Lopes Pereira Luiz Carlos Barboza Júnior
Árvores Introdução e Aplicações Árvores de Busca Binária Fundamentos
Auditoria de Segurança da Informação
Exemplos de 3 posições relativas de prédio fronteiro
Mais sobre classes Baseada no Livro: Deitel&Deitel - C++ How To program Cap. 7 Prentice Hall 1994 SCE 213 Programação Orientada a Objetos, ICMC - USP 2.
Exemplo: ordenação de uma lista pelo Selection-Sort:
Capítulo V Análise Sintática
1 Definição de Dicionário Dicionário é um sistema de informações: Equivalente a um conjunto de elementos não repetidos Equivalente a um conjunto de elementos.
Caminhamentos e Construção
Frações Professor: Graciano Pianezzer Beletti.
Programação Baseada em Objectos Desenho de TAD
Classes e objetos Arrays e Sobrecarga
Herança P. O. O. Prof. Ângela e Grace.
Classes e objetos P. O. O. Prof. Grace.
Prof. Ernesto Lindstaedt
© GfK 2012 | Title of presentation | DD. Month
Arquitetura de Sistemas Operacionais – Machado/Maia 10/1 Arquitetura de Sistemas Operacionais Francis Berenger Machado Luiz Paulo Maia Capítulo 10 Gerência.
Sincronização com Locks. Locks É um mecanismo de sincronização de processos/threads em que estas devem ser programadas de modo que seus efeitos sobre.
MECÂNICA - DINÂMICA Cinemática de uma Partícula Cap Exercícios.
Árvores binárias de pesquisa com balanceamento
INPE / CAP-315 Airam J. Preto, Celso L. Mendes Aula 30 (1) Empacotamento de Dados em MPI Tópicos: Buffer de Mensagem Empacotamento/Desempacotamento.
1 António Arnaut Duarte. 2 Sumário: primeiros passos;primeiros passos formatar fundo;formatar fundo configurar apresentação;configurar apresentação animação.
Estruturas de Dados com Jogos
Salas de Matemática.
MINISTÉRIO DO PLANEJAMENTO Projeto de Lei Orçamentária 2010 Ministro Paulo Bernardo Silva Brasília, 31 de agosto de 2009.
Principais operações em Listas TPA Listas Simples Inserção no Final 1.void insereNofinalDaLista(Lista *l, Elemento e){ 2.Lista paux,p; 3. p.
Entendendo as definições de classe
Análise Sintática – Parte 1
Scala Bruno Barros e Rebeka Gomes
1 2 Observa ilustração. Cria um texto. Observa ilustração.
Grupo A – Azul Claro, Marrom, Laranja
Os métodos equals() e hashCode()
CALENDÁRIO SEXY Ele & Ela. CALENDÁRIO SEXY Ele & Ela.
Orientação a Objetos e Java Graduação em Ciência da Computação
Java Generics Adeline de Sousa Silva.
ArrayList e Genéricos Profs. PROG2 - UNISINOS.
Tipos Especiais de Listas
Marca do evento Calendário de reuniões e encontros para o ano de 2011 Calendário 2011.
Rio Verde - Goiás - Brasil
Listas Simplesmente Encadeadas
Nome alunos 1 Título UC. Título – slide 2 Conteúdo Conteúdo 2.
POTENCIAÇÃO E RAIZ QUADRADA DE NÚMEROS RACIONAIS
GINÁSTICA LABORAL UM NOVO CAMINHO.
Árvores Binárias Profa. Patrícia A. Jaques Luiz Gonzaga Jr
Universidade do Vale do Rio dos Sinos - São Leopoldo -
Programação II Prof. Mateus Raeder Universidade do Vale do Rio dos Sinos - São Leopoldo -
Transcrição da apresentação:

ADT – Arvore Binária de Pesquisa ATAI

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

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

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

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

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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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

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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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: 2.1. If curr is null, terminate with answer none. 2.2. Otherwise, if target is equal to curr’s element, terminate with answer curr. 2.3. Otherwise, if target is less than curr’s element, set curr to curr’s left child. 2.4. 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

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.

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

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.

Remover elemento numa BST (exemplos)

Remover elemento numa BST (exemplos)

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

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

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 }

Implementação: versão iterativa

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

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

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(); } }

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(); } }

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

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(); }

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; } }

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; } }

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(); } }

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()); } }

Implementação: versão recursiva

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;

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();

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() );