|
| 1 | +# Árvore de Pesquisa Binária (Binary Search Tree) |
| 2 | + |
| 3 | +_Leia em outro idioma:_ |
| 4 | +[_English_](README.md) |
| 5 | + |
| 6 | +Na ciência da computação **binary search trees** (BST), algumas vezes |
| 7 | +chamadas de árvores binárias ordenadas (_ordered or sorted binary trees_), |
| 8 | +é um tipo particular de container: estruturas de dados que armazenam |
| 9 | +"itens" (como números, nomes, etc.) na memória. Permite pesquisa rápida, |
| 10 | +adição e remoção de itens além de poder ser utilizado para implementar |
| 11 | +tanto conjuntos dinâmicos de itens ou, consultar tabelas que permitem |
| 12 | +encontrar um item por seu valor chave. E.g. encontrar o número de |
| 13 | +telefone de uma pessoa pelo seu nome. |
| 14 | + |
| 15 | +Árvore de Pesquisa Binária mantem seus valores chaves ordenados, para |
| 16 | +que uma pesquisa e outras operações possam usar o princípio da pesquisa |
| 17 | +binária: quando pesquisando por um valor chave na árvore (ou um lugar |
| 18 | +para inserir uma nova chave), eles atravessam a árvore da raiz para a folha, |
| 19 | +fazendo comparações com chaves armazenadas nos nós da árvore e decidindo então, |
| 20 | +com base nas comparações, continuar pesquisando nas sub-árvores a direita ou |
| 21 | +a esquerda. Em média isto significa que cara comparação permite as operações |
| 22 | +pular metade da árvore, para que então, cada pesquisa, inserção ou remoção |
| 23 | +consuma tempo proporcional ao logaritmo do número de itens armazenados na |
| 24 | +árvore. Isto é muito melhor do que um tempo linear necessário para encontrar |
| 25 | +itens por seu valor chave em um array (desorndenado - _unsorted_), mas muito |
| 26 | +mais lento do que operações similares em tableas de hash (_hash tables_). |
| 27 | + |
| 28 | +Uma pesquisa de árvore binária de tamanho 9 e profundidade 3, com valor 8 |
| 29 | +na raíz. |
| 30 | +As folhas não foram desenhadas. |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +## Pseudocódigo para Operações Básicas |
| 36 | + |
| 37 | +### Inserção |
| 38 | + |
| 39 | +```text |
| 40 | +insert(value) |
| 41 | + Pre: value has passed custom type checks for type T |
| 42 | + Post: value has been placed in the correct location in the tree |
| 43 | + if root = ø |
| 44 | + root ← node(value) |
| 45 | + else |
| 46 | + insertNode(root, value) |
| 47 | + end if |
| 48 | +end insert |
| 49 | +``` |
| 50 | + |
| 51 | +```text |
| 52 | +insertNode(current, value) |
| 53 | + Pre: current is the node to start from |
| 54 | + Post: value has been placed in the correct location in the tree |
| 55 | + if value < current.value |
| 56 | + if current.left = ø |
| 57 | + current.left ← node(value) |
| 58 | + else |
| 59 | + InsertNode(current.left, value) |
| 60 | + end if |
| 61 | + else |
| 62 | + if current.right = ø |
| 63 | + current.right ← node(value) |
| 64 | + else |
| 65 | + InsertNode(current.right, value) |
| 66 | + end if |
| 67 | + end if |
| 68 | +end insertNode |
| 69 | +``` |
| 70 | + |
| 71 | +### Pesquisa |
| 72 | + |
| 73 | +```text |
| 74 | +contains(root, value) |
| 75 | + Pre: root is the root node of the tree, value is what we would like to locate |
| 76 | + Post: value is either located or not |
| 77 | + if root = ø |
| 78 | + return false |
| 79 | + end if |
| 80 | + if root.value = value |
| 81 | + return true |
| 82 | + else if value < root.value |
| 83 | + return contains(root.left, value) |
| 84 | + else |
| 85 | + return contains(root.right, value) |
| 86 | + end if |
| 87 | +end contains |
| 88 | +``` |
| 89 | + |
| 90 | + |
| 91 | +### Remoção |
| 92 | + |
| 93 | +```text |
| 94 | +remove(value) |
| 95 | + Pre: value is the value of the node to remove, root is the node of the BST |
| 96 | + count is the number of items in the BST |
| 97 | + Post: node with value is removed if found in which case yields true, otherwise false |
| 98 | + nodeToRemove ← findNode(value) |
| 99 | + if nodeToRemove = ø |
| 100 | + return false |
| 101 | + end if |
| 102 | + parent ← findParent(value) |
| 103 | + if count = 1 |
| 104 | + root ← ø |
| 105 | + else if nodeToRemove.left = ø and nodeToRemove.right = ø |
| 106 | + if nodeToRemove.value < parent.value |
| 107 | + parent.left ← nodeToRemove.right |
| 108 | + else |
| 109 | + parent.right ← nodeToRemove.right |
| 110 | + end if |
| 111 | + else if nodeToRemove.left != ø and nodeToRemove.right != ø |
| 112 | + next ← nodeToRemove.right |
| 113 | + while next.left != ø |
| 114 | + next ← next.left |
| 115 | + end while |
| 116 | + if next != nodeToRemove.right |
| 117 | + remove(next.value) |
| 118 | + nodeToRemove.value ← next.value |
| 119 | + else |
| 120 | + nodeToRemove.value ← next.value |
| 121 | + nodeToRemove.right ← nodeToRemove.right.right |
| 122 | + end if |
| 123 | + else |
| 124 | + if nodeToRemove.left = ø |
| 125 | + next ← nodeToRemove.right |
| 126 | + else |
| 127 | + next ← nodeToRemove.left |
| 128 | + end if |
| 129 | + if root = nodeToRemove |
| 130 | + root = next |
| 131 | + else if parent.left = nodeToRemove |
| 132 | + parent.left = next |
| 133 | + else if parent.right = nodeToRemove |
| 134 | + parent.right = next |
| 135 | + end if |
| 136 | + end if |
| 137 | + count ← count - 1 |
| 138 | + return true |
| 139 | +end remove |
| 140 | +``` |
| 141 | + |
| 142 | +### Encontrar o Nó Pai |
| 143 | + |
| 144 | +```text |
| 145 | +findParent(value, root) |
| 146 | + Pre: value is the value of the node we want to find the parent of |
| 147 | + root is the root node of the BST and is != ø |
| 148 | + Post: a reference to the prent node of value if found; otherwise ø |
| 149 | + if value = root.value |
| 150 | + return ø |
| 151 | + end if |
| 152 | + if value < root.value |
| 153 | + if root.left = ø |
| 154 | + return ø |
| 155 | + else if root.left.value = value |
| 156 | + return root |
| 157 | + else |
| 158 | + return findParent(value, root.left) |
| 159 | + end if |
| 160 | + else |
| 161 | + if root.right = ø |
| 162 | + return ø |
| 163 | + else if root.right.value = value |
| 164 | + return root |
| 165 | + else |
| 166 | + return findParent(value, root.right) |
| 167 | + end if |
| 168 | + end if |
| 169 | +end findParent |
| 170 | +``` |
| 171 | + |
| 172 | +### Encontrar um Nó |
| 173 | + |
| 174 | +```text |
| 175 | +findNode(root, value) |
| 176 | + Pre: value is the value of the node we want to find the parent of |
| 177 | + root is the root node of the BST |
| 178 | + Post: a reference to the node of value if found; otherwise ø |
| 179 | + if root = ø |
| 180 | + return ø |
| 181 | + end if |
| 182 | + if root.value = value |
| 183 | + return root |
| 184 | + else if value < root.value |
| 185 | + return findNode(root.left, value) |
| 186 | + else |
| 187 | + return findNode(root.right, value) |
| 188 | + end if |
| 189 | +end findNode |
| 190 | +``` |
| 191 | + |
| 192 | +### Encontrar Mínimo |
| 193 | + |
| 194 | +```text |
| 195 | +findMin(root) |
| 196 | + Pre: root is the root node of the BST |
| 197 | + root = ø |
| 198 | + Post: the smallest value in the BST is located |
| 199 | + if root.left = ø |
| 200 | + return root.value |
| 201 | + end if |
| 202 | + findMin(root.left) |
| 203 | +end findMin |
| 204 | +``` |
| 205 | + |
| 206 | +### Encontrar Máximo |
| 207 | + |
| 208 | +```text |
| 209 | +findMax(root) |
| 210 | + Pre: root is the root node of the BST |
| 211 | + root = ø |
| 212 | + Post: the largest value in the BST is located |
| 213 | + if root.right = ø |
| 214 | + return root.value |
| 215 | + end if |
| 216 | + findMax(root.right) |
| 217 | +end findMax |
| 218 | +``` |
| 219 | + |
| 220 | +### Traversal |
| 221 | + |
| 222 | +#### Na Ordem Traversal (InOrder Traversal) |
| 223 | + |
| 224 | +```text |
| 225 | +inorder(root) |
| 226 | + Pre: root is the root node of the BST |
| 227 | + Post: the nodes in the BST have been visited in inorder |
| 228 | + if root = ø |
| 229 | + inorder(root.left) |
| 230 | + yield root.value |
| 231 | + inorder(root.right) |
| 232 | + end if |
| 233 | +end inorder |
| 234 | +``` |
| 235 | + |
| 236 | +#### Pré Ordem Traversal (PreOrder Traversal) |
| 237 | + |
| 238 | +```text |
| 239 | +preorder(root) |
| 240 | + Pre: root is the root node of the BST |
| 241 | + Post: the nodes in the BST have been visited in preorder |
| 242 | + if root = ø |
| 243 | + yield root.value |
| 244 | + preorder(root.left) |
| 245 | + preorder(root.right) |
| 246 | + end if |
| 247 | +end preorder |
| 248 | +``` |
| 249 | + |
| 250 | +#### Pós Ordem Traversal (PostOrder Traversal) |
| 251 | + |
| 252 | +```text |
| 253 | +postorder(root) |
| 254 | + Pre: root is the root node of the BST |
| 255 | + Post: the nodes in the BST have been visited in postorder |
| 256 | + if root = ø |
| 257 | + postorder(root.left) |
| 258 | + postorder(root.right) |
| 259 | + yield root.value |
| 260 | + end if |
| 261 | +end postorder |
| 262 | +``` |
| 263 | + |
| 264 | +## Complexidades |
| 265 | + |
| 266 | +### Complexidade de Tempo |
| 267 | + |
| 268 | +| Access | Search | Insertion | Deletion | |
| 269 | +| :-------: | :-------: | :-------: | :-------: | |
| 270 | +| O(log(n)) | O(log(n)) | O(log(n)) | O(log(n)) | |
| 271 | + |
| 272 | +### Complexidade de Espaço |
| 273 | + |
| 274 | +O(n) |
| 275 | + |
| 276 | +## Referências |
| 277 | + |
| 278 | +- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_tree) |
| 279 | +- [Inserting to BST on YouTube](https://www.youtube.com/watch?v=wcIRPqTR3Kc&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=9&t=0s) |
| 280 | +- [BST Interactive Visualisations](https://www.cs.usfca.edu/~galles/visualization/BST.html) |
0 commit comments