Adds Portuguese (pt-BR) translation (#340)

* create portuguese translations

* renames `Lista Ligada` to `Lista Encadeada`

* revert changes on package-lock.json
This commit is contained in:
Marcos Gonçalves
2019-04-16 16:47:04 +02:00
committed by Oleksii Trekhleb
parent 1520533d11
commit ed99f9d216
35 changed files with 1110 additions and 62 deletions

View File

@@ -1,5 +1,8 @@
# Tree
_Read this in other languages:_
[_简体中文_](README.zh-CN.md) | [_Português_](README.pt-BR.md)
* [Binary Search Tree](binary-search-tree)
* [AVL Tree](avl-tree)
* [Red-Black Tree](red-black-tree)

View File

@@ -0,0 +1,33 @@
# Árvore (Tree)
_Leia em outro idioma:_
[_English_](README.md) | [_简体中文_](README.zh-CN.md)
* [Árvore de Pesquisa Binária (Binary Search Tree)](binary-search-tree/README.pt-BR.md)
* [Árvore AVL (AVL Tree)](avl-tree/README.pt-BR.md)
* [Árvore Vermelha-Preta (Red-Black Tree)](red-black-tree/README.pt-BR.md)
* [Árvore de Segmento (Segment Tree)](segment-tree/README.pt-BR.md) - com exemplos de consulta de intervalores min/max/sum
* [Árvorem Fenwick (Fenwick Tree)](fenwick-tree/README.pt-BR.md) (Árvore Binária Indexada / Binary Indexed Tree)
Na ciência da computação, uma **árvore** é uma estrutura de dados
abstrada (ADT) amplamente utilizada - ou uma estrutura de dados
implementando este ADT que simula uma estrutura hierarquica de árvore,
com valor raíz e sub-árvores de filhos com um nó pai, representado
como um conjunto de nós conectados.
Uma estrutura de dados em árvore pode ser definida recursivamente como
(localmente) uma coleção de nós (começando no nó raíz), aonde cada nó
é uma estrutura de dados consistindo de um valor, junto com uma lista
de referências aos nós (os "filhos"), com as restrições de que nenhuma
referência é duplicada e nenhuma aponta para a raiz.
Uma árvore não ordenada simples; neste diagrama, o nó rotulado como `7`
possui dois filhos, rotulados como `2` e `6`, e um pai, rotulado como `2`.
O nó raíz, no topo, não possui nenhum pai.
![Tree](https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg)
## Referências
- [Wikipedia](https://en.wikipedia.org/wiki/Tree_(data_structure))
- [YouTube](https://www.youtube.com/watch?v=oSWTXtMglKE&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=8)

View File

@@ -1,5 +1,8 @@
# AVL Tree
_Read this in other languages:_
[_Português_](README.pt-BR.md)
In computer science, an **AVL tree** (named after inventors
Adelson-Velsky and Landis) is a self-balancing binary search
tree. It was the first such data structure to be invented.

View File

@@ -0,0 +1,53 @@
# Árvore AVL (AVL Tree)
_Leia em outro idioma:_
[_English_](README.md)
Na ciência da computação, uma **árvore AVL** (em homenagem aos
inventores Adelson-Velsky e Landis) é uma árvore de pesquisa
binária auto balanceada. Foi a primeira estrutura de dados a
ser inventada.
Em uma árvore AVL, as alturas de duas sub-árvores filhas
de qualquer nó diferem no máximo em um; se a qualquer momento
diferirem por em mais de um, um rebalanceamento é feito para
restaurar esta propriedade.
Pesquisa, inserção e exclusão possuem tempo `O(log n)` tanto na
média quanto nos piores casos, onde `n` é o número de nós na
árvore antes da operação. Inserções e exclusões podem exigir
que a árvore seja reequilibrada por uma ou mais rotações.
Animação mostrando a inserção de vários elementos em uma árvore AVL.
Inclui as rotações de esquerda, direita, esquerda-direita e direita-esquerda.
![AVL Tree](https://upload.wikimedia.org/wikipedia/commons/f/fd/AVL_Tree_Example.gif)
Árvore AVL com fatores de equilíbrio (verde)
![AVL Tree](https://upload.wikimedia.org/wikipedia/commons/a/ad/AVL-tree-wBalance_K.svg)
### Rotações de Árvores AVL
**Rotação Esquerda-Esquerda**
![Left-Left Rotation](http://btechsmartclass.com/data_structures/ds_images/LL%20Rotation.png)
**Rotação direita-direita**
![Right-Right Rotation](http://btechsmartclass.com/data_structures/ds_images/RR%20Rotation.png)
**Rotação Esquerda-Direita**
![Left-Right Rotation](http://btechsmartclass.com/data_structures/ds_images/LR%20Rotation.png)
**Rotação Direita-Esquerda**
![Right-Right Rotation](http://btechsmartclass.com/data_structures/ds_images/RL%20Rotation.png)
## Referências
* [Wikipedia](https://en.wikipedia.org/wiki/AVL_tree)
* [Tutorials Point](https://www.tutorialspoint.com/data_structures_algorithms/avl_tree_algorithm.htm)
* [BTech](http://btechsmartclass.com/data_structures/avl-trees.html)
* [AVL Tree Insertion on YouTube](https://www.youtube.com/watch?v=rbg7Qf8GkQ4&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=12&)
* [AVL Tree Interactive Visualisations](https://www.cs.usfca.edu/~galles/visualization/AVLtree.html)

View File

@@ -1,5 +1,8 @@
# Binary Search Tree
_Read this in other languages:_
[_Português_](README.pt-BR.md)
In computer science, **binary search trees** (BST), sometimes called
ordered or sorted binary trees, are a particular type of container:
data structures that store "items" (such as numbers, names etc.)

View File

@@ -0,0 +1,280 @@
# Árvore de Pesquisa Binária (Binary Search Tree)
_Leia em outro idioma:_
[_English_](README.md)
Na ciência da computação **binary search trees** (BST), algumas vezes
chamadas de árvores binárias ordenadas (_ordered or sorted binary trees_),
é um tipo particular de container: estruturas de dados que armazenam
"itens" (como números, nomes, etc.) na memória. Permite pesquisa rápida,
adição e remoção de itens além de poder ser utilizado para implementar
tanto conjuntos dinâmicos de itens ou, consultar tabelas que permitem
encontrar um item por seu valor chave. E.g. encontrar o número de
telefone de uma pessoa pelo seu nome.
Árvore de Pesquisa Binária mantem seus valores chaves ordenados, para
que uma pesquisa e outras operações possam usar o princípio da pesquisa
binária: quando pesquisando por um valor chave na árvore (ou um lugar
para inserir uma nova chave), eles atravessam a árvore da raiz para a folha,
fazendo comparações com chaves armazenadas nos nós da árvore e decidindo então,
com base nas comparações, continuar pesquisando nas sub-árvores a direita ou
a esquerda. Em média isto significa que cara comparação permite as operações
pular metade da árvore, para que então, cada pesquisa, inserção ou remoção
consuma tempo proporcional ao logaritmo do número de itens armazenados na
árvore. Isto é muito melhor do que um tempo linear necessário para encontrar
itens por seu valor chave em um array (desorndenado - _unsorted_), mas muito
mais lento do que operações similares em tableas de hash (_hash tables_).
Uma pesquisa de árvore binária de tamanho 9 e profundidade 3, com valor 8
na raíz.
As folhas não foram desenhadas.
![Binary Search Tree](https://upload.wikimedia.org/wikipedia/commons/d/da/Binary_search_tree.svg)
## Pseudocódigo para Operações Básicas
### Inserção
```text
insert(value)
Pre: value has passed custom type checks for type T
Post: value has been placed in the correct location in the tree
if root = ø
root ← node(value)
else
insertNode(root, value)
end if
end insert
```
```text
insertNode(current, value)
Pre: current is the node to start from
Post: value has been placed in the correct location in the tree
if value < current.value
if current.left = ø
current.left ← node(value)
else
InsertNode(current.left, value)
end if
else
if current.right = ø
current.right ← node(value)
else
InsertNode(current.right, value)
end if
end if
end insertNode
```
### Pesquisa
```text
contains(root, value)
Pre: root is the root node of the tree, value is what we would like to locate
Post: value is either located or not
if root = ø
return false
end if
if root.value = value
return true
else if value < root.value
return contains(root.left, value)
else
return contains(root.right, value)
end if
end contains
```
### Remoção
```text
remove(value)
Pre: value is the value of the node to remove, root is the node of the BST
count is the number of items in the BST
Post: node with value is removed if found in which case yields true, otherwise false
nodeToRemove ← findNode(value)
if nodeToRemove = ø
return false
end if
parent ← findParent(value)
if count = 1
root ← ø
else if nodeToRemove.left = ø and nodeToRemove.right = ø
if nodeToRemove.value < parent.value
parent.left ← nodeToRemove.right
else
parent.right ← nodeToRemove.right
end if
else if nodeToRemove.left != ø and nodeToRemove.right != ø
next ← nodeToRemove.right
while next.left != ø
next ← next.left
end while
if next != nodeToRemove.right
remove(next.value)
nodeToRemove.value ← next.value
else
nodeToRemove.value ← next.value
nodeToRemove.right ← nodeToRemove.right.right
end if
else
if nodeToRemove.left = ø
next ← nodeToRemove.right
else
next ← nodeToRemove.left
end if
if root = nodeToRemove
root = next
else if parent.left = nodeToRemove
parent.left = next
else if parent.right = nodeToRemove
parent.right = next
end if
end if
count ← count - 1
return true
end remove
```
### Encontrar o Nó Pai
```text
findParent(value, root)
Pre: value is the value of the node we want to find the parent of
root is the root node of the BST and is != ø
Post: a reference to the prent node of value if found; otherwise ø
if value = root.value
return ø
end if
if value < root.value
if root.left = ø
return ø
else if root.left.value = value
return root
else
return findParent(value, root.left)
end if
else
if root.right = ø
return ø
else if root.right.value = value
return root
else
return findParent(value, root.right)
end if
end if
end findParent
```
### Encontrar um Nó
```text
findNode(root, value)
Pre: value is the value of the node we want to find the parent of
root is the root node of the BST
Post: a reference to the node of value if found; otherwise ø
if root = ø
return ø
end if
if root.value = value
return root
else if value < root.value
return findNode(root.left, value)
else
return findNode(root.right, value)
end if
end findNode
```
### Encontrar Mínimo
```text
findMin(root)
Pre: root is the root node of the BST
root = ø
Post: the smallest value in the BST is located
if root.left = ø
return root.value
end if
findMin(root.left)
end findMin
```
### Encontrar Máximo
```text
findMax(root)
Pre: root is the root node of the BST
root = ø
Post: the largest value in the BST is located
if root.right = ø
return root.value
end if
findMax(root.right)
end findMax
```
### Traversal
#### Na Ordem Traversal (InOrder Traversal)
```text
inorder(root)
Pre: root is the root node of the BST
Post: the nodes in the BST have been visited in inorder
if root = ø
inorder(root.left)
yield root.value
inorder(root.right)
end if
end inorder
```
#### Pré Ordem Traversal (PreOrder Traversal)
```text
preorder(root)
Pre: root is the root node of the BST
Post: the nodes in the BST have been visited in preorder
if root = ø
yield root.value
preorder(root.left)
preorder(root.right)
end if
end preorder
```
#### Pós Ordem Traversal (PostOrder Traversal)
```text
postorder(root)
Pre: root is the root node of the BST
Post: the nodes in the BST have been visited in postorder
if root = ø
postorder(root.left)
postorder(root.right)
yield root.value
end if
end postorder
```
## Complexidades
### Complexidade de Tempo
| Access | Search | Insertion | Deletion |
| :-------: | :-------: | :-------: | :-------: |
| O(log(n)) | O(log(n)) | O(log(n)) | O(log(n)) |
### Complexidade de Espaço
O(n)
## Referências
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_tree)
- [Inserting to BST on YouTube](https://www.youtube.com/watch?v=wcIRPqTR3Kc&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=9&t=0s)
- [BST Interactive Visualisations](https://www.cs.usfca.edu/~galles/visualization/BST.html)

View File

@@ -1,5 +1,8 @@
# Fenwick Tree / Binary Indexed Tree
_Leia em outro idioma:_
[_English_](README.pt-BR.md)
A **Fenwick tree** or **binary indexed tree** is a data
structure that can efficiently update elements and
calculate prefix sums in a table of numbers.

View File

@@ -0,0 +1,45 @@
# Árvore Fenwick / Árvore Binária Indexada (Fenwick Tree / Binary Indexed Tree)
_Read this in other languages:_
[_Português_](README.md)
Uma **árvore Fenwick** ou **árvore binária indexada** é um tipo de
estrutura de dados que consegue eficiemente atualizar elementos e
calcular soma dos prefixos em uma tabela de números.
Quando comparado com um _flat array_ de números, a árvore Fenwick
alcança um balanceamento muito melhor entre duas operações: atualização
(_update_) do elemento e cálculo da soma do prefíxo. Em uma _flar array_
de `n` números, você pode tanto armazenar elementos quando a soma dos
prefixos. Em ambos os casos, computar a soma dos prefixos requer ou
atualizar um array de elementos também requerem um tempo linear, contudo,
a demais operações podem ser realizadas com tempo constante.
A árvore Fenwick permite ambas as operações serem realizadas com tempo
`O(log n)`.
Isto é possível devido a representação dos números como uma árvore, aonde
os valores de cada nó é a soma dos números naquela sub-árvore. A estrutura
de árvore permite operações a serem realizadas consumindo somente acessos
a nós em `O(log n)`.
## Implementação de Nós
Árvore Binária Indexada é representada como um _array_. Em cada nó da Árvore
Binária Indexada armazena a soma de alguns dos elementos de uma _array_
fornecida. O tamanho da Árvore Binária Indexada é igual a `n` aonde `n` é o
tamanho do _array_ de entrada. Na presente implementação nós utilizados o
tamanho `n+1` para uma implementação fácil. Todos os índices são baseados em 1.
![Binary Indexed Tree](https://www.geeksforgeeks.org/wp-content/uploads/BITSum.png)
Na imagem abaixo você pode ver o exemplo animado da criação de uma árvore
binária indexada para o _array_ `[1, 2, 3, 4, 5]`, sendo inseridos um após
o outro.
![Fenwick Tree](https://upload.wikimedia.org/wikipedia/commons/d/dc/BITDemo.gif)
## Referências
- [Wikipedia](https://en.wikipedia.org/wiki/Fenwick_tree)
- [GeeksForGeeks](https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/)
- [YouTube](https://www.youtube.com/watch?v=CWDQJGaN1gY&index=18&t=0s&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

View File

@@ -1,5 +1,8 @@
# RedBlack Tree
_Leia em outro idioma:_
[_English_](README.pt-BR.md)
A **redblack tree** is a kind of self-balancing binary search
tree in computer science. Each node of the binary tree has
an extra bit, and that bit is often interpreted as the

View File

@@ -0,0 +1,95 @@
# Árvore Vermelha-Preta (Red-Black Tree)
_Read this in other languages:_
[_Português_](README.md)
Uma **árvore vermelha-preta** é um tipo de árvore de pesquisa
binária auto balanceada na ciência da computação. Cada nó da
árvore binária possui um _bit_ extra, e este _bit_ é frequentemente
interpretado com a cor (vermelho ou preto) do nó. Estas cores de _bits_
são utilizadas para garantir que a árvore permanece aproximadamente
equilibrada durante as operações de inserções e remoções.
O equilíbrio é preservado através da pintura de cada nó da árvore com
uma das duas cores, de maneira que satisfaça certas propriedades, das
quais restringe nos piores dos casos, o quão desequilibrada a árvore
pode se tornar. Quando a árvore é modificada, a nova árvore é
subsequentemente reorganizada e repintada para restaurar as
propriedades de coloração. As propriedades são designadas de tal modo que
esta reorganização e nova pintura podem ser realizadas eficientemente.
O balanceamento de uma árvore não é perfeito, mas é suficientemente bom
para permitir e garantir uma pesquisa no tempo `O(log n)`, aonde `n` é o
número total de elementos na árvore.
Operações de inserções e remoções, juntamente com a reorganização e
repintura da árvore, também são executados no tempo `O (log n)`.
Um exemplo de uma árvore vermalha-preta:
![red-black tree](https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg)
## Propriedades
Em adição aos requerimentos impostos pela árvore de pesquisa binária,
as seguintes condições devem ser satisfeitas pela árvore vermelha-preta:
- Cada nó é tanto vermelho ou preto.
- O nó raíz é preto. Esta regra algumas vezes é omitida.
Tendo em vista que a raíz pode sempre ser alterada de vermelho para preto,
mas não de preto para vermelho, esta regra tem pouco efeito na análise.
- Todas as folhas (Nulo/NIL) são pretas.
- Caso um nó é vermelho, então seus filhos serão pretos.
- Cada caminho de um determinado nó para qualquer um dos seus nós nulos (NIL)
descendentes contém o mesmo número de nós pretos.
Algumas definições: o número de nós pretos da raiz até um nó é a
**profundidade preta**(_black depth_) do nó; o número uniforme de nós pretos
em todos os caminhos da raíz até as folhas são chamados de **altura negra**
(_black-height_) da árvore vermelha-preta.
Essas restrições impõem uma propriedade crítica de árvores vermelhas e pretas:
_o caminho da raiz até a folha mais distante não possui mais que o dobro do
comprimento do caminho da raiz até a folha mais próxima_.
O resultado é que a árvore é grosseiramente balanceada na altura.
Tendo em vista que operações como inserções, remoção e pesquisa de valores
requerem nos piores dos casos um tempo proporcional a altura da ávore,
este limite superior teórico na altura permite que as árvores vermelha-preta
sejam eficientes no pior dos casos, ao contrário das árvores de busca binária
comuns.
## Balanceamento durante a inserção
### Se o tio é VERMELHO
![Red Black Tree Balancing](https://www.geeksforgeeks.org/wp-content/uploads/redBlackCase2.png)
### Se o tio é PRETO
- Caso Esquerda Esquerda (`p` é o filho a esquerda de `g` e `x`, é o filho a esquerda de `p`)
- Caso Esquerda Direita (`p` é o filho a esquerda de `g` e `x`, é o filho a direita de `p`)
- Caso Direita Direita (`p` é o filho a direita de `g` e `x`, é o filho da direita de `p`)
- Caso Direita Esqueda (`p` é o filho a direita de `g` e `x`, é o filho a esquerda de `p`)
#### Caso Esquerda Esquerda (Veja g, p e x)
![Red Black Tree Balancing](https://www.geeksforgeeks.org/wp-content/uploads/redBlackCase3a1.png)
#### Caso Esquerda Direita (Veja g, p e x)
![Red Black Tree Balancing](https://www.geeksforgeeks.org/wp-content/uploads/redBlackCase3b.png)
#### Caso Direita Direita (Veja g, p e x)
![Red Black Tree Balancing](https://www.geeksforgeeks.org/wp-content/uploads/redBlackCase3c.png)
#### Caso Direita Esquerda (Veja g, p e x)
![Red Black Tree Balancing](https://www.geeksforgeeks.org/wp-content/uploads/redBlackCase3d.png)
## Referências
- [Wikipedia](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree)
- [Red Black Tree Insertion by Tushar Roy (YouTube)](https://www.youtube.com/watch?v=UaLIHuR1t8Q&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=63)
- [Red Black Tree Deletion by Tushar Roy (YouTube)](https://www.youtube.com/watch?v=CTvfzU_uNKE&t=0s&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=64)
- [Red Black Tree Insertion on GeeksForGeeks](https://www.geeksforgeeks.org/red-black-tree-set-2-insert/)
- [Red Black Tree Interactive Visualisations](https://www.cs.usfca.edu/~galles/visualization/RedBlack.html)

View File

@@ -1,5 +1,8 @@
# Segment Tree
_Leia em outro idioma:_
[_English_](README.pt-BR.md)
In computer science, a **segment tree** also known as a statistic tree
is a tree data structure used for storing information about intervals,
or segments. It allows querying which of the stored segments contain

View File

@@ -0,0 +1,51 @@
# Árvore de Segmento (Segment Tree)
_Read this in other languages:_
[_Português_](README.md)
Na ciência da computação, uma **árvore de segmento** também conhecida como
árvore estatística é uma árvore de estrutura de dados utilizadas para
armazenar informações sobre intervalores ou segmentos. Ela permite pesquisas
no qual os segmentos armazenados contém um ponto fornecido. Isto é,
em princípio, uma estrutura estática; ou seja, é uma estrutura que não pode
ser modificada depois de inicializada. Uma estrutura de dados similar é a
árvore de intervalos.
Uma árvore de segmento é uma árvore binária. A raíz da árvore representa a
_array_ inteira. Os dois filhos da raíz representam a primeira e a segunda
metade da _array_. Similarmente, os filhos de cada nó correspondem ao número
das duas metadas da _array_ correspondente do nó.
Nós construímos a árvore debaixo para cima, com o valor de cada nó sendo o
"mínimo" (ou qualquer outra função) dos valores de seus filhos. Isto consumirá
tempo `O(n log n)`. O número de oprações realizadas é equivalente a altura da
árvore, pela qual consome tempo `O(log n)`. Para fazer consultas de intervalos,
cada nó divide a consulta em duas partes, sendo uma sub consulta para cada filho.
Se uma pesquisa contém todo o _subarray_ de um nó, nós podemos utilizar do valor
pré-calculado do nó. Utilizando esta otimização, nós podemos provar que somente
operações mínimas `O(log n)` são realizadas.
![Min Segment Tree](https://www.geeksforgeeks.org/wp-content/uploads/RangeMinimumQuery.png)
![Sum Segment Tree](https://www.geeksforgeeks.org/wp-content/uploads/segment-tree1.png)
## Aplicação
Uma árvore de segmento é uma estrutura de dados designada a realizar
certas operações de _array_ eficientemente, especialmente aquelas envolvendo
consultas de intervalos.
Aplicações da árvore de segmentos são nas áreas de computação geométrica e
sistemas de informação geográficos.
A implementação atual da Árvore de Segmentos implica que você pode passar
qualquer função binária (com dois parâmetros de entradas) e então, você
será capaz de realizar consultas de intervalos para uma variedade de funções.
Nos testes você poderá encontrar exemplos realizando `min`, `max` e consultas de
intervalo `sam` na árvore segmentada (SegmentTree).
## Referências
- [Wikipedia](https://en.wikipedia.org/wiki/Segment_tree)
- [YouTube](https://www.youtube.com/watch?v=ZBHKZF5w4YU&index=65&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
- [GeeksForGeeks](https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/)