mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Merge branch 'master' into master
This commit is contained in:
commit
7844a35ad0
@ -1,23 +1,25 @@
|
|||||||
# Graph
|
# Graph
|
||||||
|
|
||||||
En informatique, un **graphe** est une structure de
|
En informatique, un **graphe** est une structure de
|
||||||
données abstraite qui implémente les concepts de
|
données abstraite qui implémente les concepts de
|
||||||
graphe orienté et de graphe non-orienté venant
|
graphe orienté et de graphe non-orienté venant
|
||||||
des mathématiques, plus précisément du domaine de
|
des mathématiques, plus précisément du domaine de
|
||||||
la théorie des graphes.
|
la théorie des graphes.
|
||||||
|
|
||||||
La structure de données abstraite de graphe consiste
|
La structure de données abstraite de graphe consiste
|
||||||
en un ensemble fini, éventuellement mutable de sommets
|
en un ensemble fini, éventuellement mutable de sommets
|
||||||
ou nœuds ou points, avec un ensemble de paires ordonnées
|
ou nœuds ou points, avec un ensemble de paires ordonnées
|
||||||
ou non de tels éléments. Ces paires sont des arêtes, arcs
|
ou non de tels éléments. Ces paires sont des arêtes, arcs
|
||||||
non orientés, ou lignes pour un graphe non orienté, et
|
non orientés, ou lignes pour un graphe non orienté, et
|
||||||
flèches, arêtes orientées , arcs, ou lignes orientées
|
flèches, arêtes orientées , arcs, ou lignes orientées
|
||||||
dans le cas orienté. Les sommets peuvent faire partie
|
dans le cas orienté. Les sommets peuvent faire partie
|
||||||
de la structure, ou être des entités extérieures,
|
de la structure, ou être des entités extérieures,
|
||||||
représentées par des entiers ou des références.
|
représentées par des entiers ou des références.
|
||||||
|
|
||||||
![Graph](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
|
![Graph](./images/graph.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
- [Wikipedia](https://fr.wikipedia.org/wiki/Graphe_(type_abstrait))
|
- [Wikipedia](https://fr.wikipedia.org/wiki/Graphe_(type_abstrait))
|
||||||
|
@ -6,23 +6,25 @@ _Read this in other languages:_
|
|||||||
[_Français_](README.fr-FR.md),
|
[_Français_](README.fr-FR.md),
|
||||||
[_Português_](README.pt-BR.md)
|
[_Português_](README.pt-BR.md)
|
||||||
|
|
||||||
In computer science, a **graph** is an abstract data type
|
In computer science, a **graph** is an abstract data type
|
||||||
that is meant to implement the undirected graph and
|
that is meant to implement the undirected graph and
|
||||||
directed graph concepts from mathematics, specifically
|
directed graph concepts from mathematics, specifically
|
||||||
the field of graph theory
|
the field of graph theory
|
||||||
|
|
||||||
A graph data structure consists of a finite (and possibly
|
A graph data structure consists of a finite (and possibly
|
||||||
mutable) set of vertices or nodes or points, together
|
mutable) set of vertices or nodes or points, together
|
||||||
with a set of unordered pairs of these vertices for an
|
with a set of unordered pairs of these vertices for an
|
||||||
undirected graph or a set of ordered pairs for a
|
undirected graph or a set of ordered pairs for a
|
||||||
directed graph. These pairs are known as edges, arcs,
|
directed graph. These pairs are known as edges, arcs,
|
||||||
or lines for an undirected graph and as arrows,
|
or lines for an undirected graph and as arrows,
|
||||||
directed edges, directed arcs, or directed lines
|
directed edges, directed arcs, or directed lines
|
||||||
for a directed graph. The vertices may be part of
|
for a directed graph. The vertices may be part of
|
||||||
the graph structure, or may be external entities
|
the graph structure, or may be external entities
|
||||||
represented by integer indices or references.
|
represented by integer indices or references.
|
||||||
|
|
||||||
![Graph](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
|
![Graph](./images/graph.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
|
@ -17,7 +17,9 @@ para um grafo direcionado.
|
|||||||
Os vértices podem fazer parte a estrutura do grafo, ou podem
|
Os vértices podem fazer parte a estrutura do grafo, ou podem
|
||||||
ser entidades externas representadas por índices inteiros ou referências.
|
ser entidades externas representadas por índices inteiros ou referências.
|
||||||
|
|
||||||
![Graph](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
|
![Graph](./images/graph.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Referências
|
## Referências
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
**Граф** в информатике - абстрактный тип данных, который должен реализовывать концепции направленного и ненаправленного
|
**Граф** в информатике - абстрактный тип данных, который должен реализовывать концепции направленного и ненаправленного
|
||||||
графа в математике, особенно в области теории графов.
|
графа в математике, особенно в области теории графов.
|
||||||
|
|
||||||
Структура данных графа состоит из конечного (и возможно изменяющегося) набора вершин или узлов, или точек, совместно с
|
Структура данных графа состоит из конечного (и возможно изменяющегося) набора вершин или узлов, или точек, совместно с
|
||||||
набором ненаправленных пар этих вершин для ненаправленного графа или с набором направленных пар для направленного графа.
|
набором ненаправленных пар этих вершин для ненаправленного графа или с набором направленных пар для направленного графа.
|
||||||
Эти пары известны как рёбра, арки или линии для ненаправленного графа и как стрелки, направленные рёбра, направленные
|
Эти пары известны как рёбра, арки или линии для ненаправленного графа и как стрелки, направленные рёбра, направленные
|
||||||
арки или направленные линии для направленного графа. Эти вершины могут быть частью структуры графа, или внешними
|
арки или направленные линии для направленного графа. Эти вершины могут быть частью структуры графа, или внешними
|
||||||
@ -14,7 +14,9 @@
|
|||||||
информатике, могут быть представлены графами. Например, строение Википедии можно смоделировать при помощи
|
информатике, могут быть представлены графами. Например, строение Википедии можно смоделировать при помощи
|
||||||
ориентированного графа, в котором вершины — это статьи, а дуги (ориентированные рёбра) — гиперссылки.
|
ориентированного графа, в котором вершины — это статьи, а дуги (ориентированные рёбра) — гиперссылки.
|
||||||
|
|
||||||
![Граф](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
|
![Граф](./images/graph.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Ссылки
|
## Ссылки
|
||||||
|
|
||||||
|
@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
如果顶点对之间的边是有权重的,该图可称为加权图。
|
如果顶点对之间的边是有权重的,该图可称为加权图。
|
||||||
|
|
||||||
|
![Graph](./images/graph.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
![Graph](https://www.tutorialspoint.com/data_structures_algorithms/images/graph.jpg)
|
|
||||||
|
|
||||||
## 参考
|
## 参考
|
||||||
|
|
||||||
|
BIN
src/data-structures/graph/images/graph.jpeg
Normal file
BIN
src/data-structures/graph/images/graph.jpeg
Normal file
Binary file not shown.
After Width: | Height: | Size: 132 KiB |
@ -17,11 +17,13 @@ hachage où la fonction de hachage génère le même index
|
|||||||
pour plusieurs clés. De telles collisions doivent être
|
pour plusieurs clés. De telles collisions doivent être
|
||||||
accommodées d'une manière ou d'une autre.
|
accommodées d'une manière ou d'une autre.
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
Collision de hachage résolue par chaînage séparé.
|
Collision de hachage résolue par chaînage séparé.
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Références
|
## Références
|
||||||
|
|
||||||
|
@ -1,14 +1,16 @@
|
|||||||
# ハッシュテーブル
|
# ハッシュテーブル
|
||||||
|
|
||||||
コンピュータサイエンスにおいて、**ハッシュテーブル**(ハッシュマップ)は*キーを値にマッピング*できる*連想配列*の機能を持ったデータ構造です。ハッシュテーブルは*ハッシュ関数*を使ってバケットやスロットの配列へのインデックスを計算し、そこから目的の値を見つけることができます。
|
コンピュータサイエンスにおいて、**ハッシュテーブル**(ハッシュマップ)は*キーを値にマッピング*できる*連想配列*の機能を持ったデータ構造です。ハッシュテーブルは*ハッシュ関数*を使ってバケットやスロットの配列へのインデックスを計算し、そこから目的の値を見つけることができます。
|
||||||
|
|
||||||
理想的には、ハッシュ関数は各キーを一意のバケットに割り当てますが、ほとんどのハッシュテーブルは不完全なハッシュ関数を採用しているため、複数のキーに対して同じインデックスを生成した時にハッシュの衝突が起こります。このような衝突は何らかの方法で対処する必要があります。
|
理想的には、ハッシュ関数は各キーを一意のバケットに割り当てますが、ほとんどのハッシュテーブルは不完全なハッシュ関数を採用しているため、複数のキーに対して同じインデックスを生成した時にハッシュの衝突が起こります。このような衝突は何らかの方法で対処する必要があります。
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
チェイン法によるハッシュの衝突の解決例
|
チェイン法によるハッシュの衝突の解決例
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## 参考
|
## 参考
|
||||||
|
|
||||||
|
@ -11,13 +11,17 @@ _Read this in other languages:_
|
|||||||
|
|
||||||
이상적으로, 해시 함수는 각 키들을 고유 버킷에 할당하지만 대부분의 해시 테이블은 불완전한 해시 함수를 사용하기 때문에 해시 함수를 통해 두 개 이상의 키에 대해 동일한 인덱스를 생성하는 해시 충돌이 발생할 수 있습니다. 이러한 해시 충돌은 어떠한 방법으로든 해결되어야 합니다.
|
이상적으로, 해시 함수는 각 키들을 고유 버킷에 할당하지만 대부분의 해시 테이블은 불완전한 해시 함수를 사용하기 때문에 해시 함수를 통해 두 개 이상의 키에 대해 동일한 인덱스를 생성하는 해시 충돌이 발생할 수 있습니다. 이러한 해시 충돌은 어떠한 방법으로든 해결되어야 합니다.
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
다음은 분리 연결법을 통해 해시 충돌을 해결한 예시입니다.
|
다음은 분리 연결법을 통해 해시 충돌을 해결한 예시입니다.
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## 참고
|
## 참고
|
||||||
|
|
||||||
- [Wikipedia](https://en.wikipedia.org/wiki/Hash_table)
|
- [Wikipedia](https://en.wikipedia.org/wiki/Hash_table)
|
||||||
- [YouTube](https://www.youtube.com/watch?v=shs0KM3wKv8&index=4&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
|
- [YouTube](https://www.youtube.com/watch?v=shs0KM3wKv8&index=4&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
|
||||||
|
@ -22,11 +22,13 @@ collisions where the hash function generates the same
|
|||||||
index for more than one key. Such collisions must be
|
index for more than one key. Such collisions must be
|
||||||
accommodated in some way.
|
accommodated in some way.
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
Hash collision resolved by separate chaining.
|
Hash collision resolved by separate chaining.
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
|
@ -13,11 +13,13 @@ imperfeita, pela qual poderá causar colisões de hashes onde a função de hash
|
|||||||
gera o mesmo índice para mais de uma chave.Tais colisões devem ser
|
gera o mesmo índice para mais de uma chave.Tais colisões devem ser
|
||||||
acomodados de alguma forma.
|
acomodados de alguma forma.
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
Colisão de hash resolvida por encadeamento separado.
|
Colisão de hash resolvida por encadeamento separado.
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Referências
|
## Referências
|
||||||
|
|
||||||
|
@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
**Хеш-таблица** - структура данных, реализующая абстрактный тип данных *ассоциативный массив*, т.е. структура, которая
|
**Хеш-таблица** - структура данных, реализующая абстрактный тип данных *ассоциативный массив*, т.е. структура, которая
|
||||||
*связывает ключи со значениями*. Хеш-таблица использует *хеш-функцию* для вычисления индекса в массиве, в котором может
|
*связывает ключи со значениями*. Хеш-таблица использует *хеш-функцию* для вычисления индекса в массиве, в котором может
|
||||||
быть найдено желаемое значение. Ниже представлена хеш-таблица, в которой ключом выступает имя человека, а значениями
|
быть найдено желаемое значение. Ниже представлена хеш-таблица, в которой ключом выступает имя человека, а значениями
|
||||||
являются телефонные номера. Хеш-функция преобразует ключ-имя в индекс массива с телефонными номерами.
|
являются телефонные номера. Хеш-функция преобразует ключ-имя в индекс массива с телефонными номерами.
|
||||||
|
|
||||||
![Хеш-таблица](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
В идеале хеш-функция будет присваивать элементу массива уникальный ключ. Однако большинство реальных хеш-таблиц
|
В идеале хеш-функция будет присваивать элементу массива уникальный ключ. Однако большинство реальных хеш-таблиц
|
||||||
используют несовершенные хеш-функции. Это может привести к ситуациям, когда хеш-функция генерирует одинаковый индекс для
|
используют несовершенные хеш-функции. Это может привести к ситуациям, когда хеш-функция генерирует одинаковый индекс для
|
||||||
@ -14,9 +14,13 @@
|
|||||||
Существует два варианта решения коллизий - хеш-таблица с цепочками и с открытой адресацией.
|
Существует два варианта решения коллизий - хеш-таблица с цепочками и с открытой адресацией.
|
||||||
|
|
||||||
Метод цепочек подразумевает хранение значений, соответствующих одному и тому же индексу в виде связного списка(цепочки).
|
Метод цепочек подразумевает хранение значений, соответствующих одному и тому же индексу в виде связного списка(цепочки).
|
||||||
![Хеш цепочки](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
|
||||||
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
Метод открытой адресации помещает значение, для которого получен дублирующий индекс, в первую свободную ячейку.
|
Метод открытой адресации помещает значение, для которого получен дублирующий индекс, в первую свободную ячейку.
|
||||||
|
|
||||||
![Хеш открытая адресация](https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Hash_table_5_0_1_1_1_1_0_SP.svg/380px-Hash_table_5_0_1_1_1_1_0_SP.svg.png)
|
![Хеш открытая адресация](https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Hash_table_5_0_1_1_1_1_0_SP.svg/380px-Hash_table_5_0_1_1_1_1_0_SP.svg.png)
|
||||||
|
|
||||||
## Ссылки
|
## Ссылки
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
# 哈希表
|
# 哈希表
|
||||||
|
|
||||||
在计算中, 一个 **哈希表(hash table 或hash map)** 是一种实现 *关联数组(associative array)*
|
在计算中, 一个 **哈希表(hash table 或hash map)** 是一种实现 *关联数组(associative array)*
|
||||||
的抽象数据类型, 该结构可以将 *键映射到值*。
|
的抽象数据类型, 该结构可以将 *键映射到值*。
|
||||||
|
|
||||||
哈希表使用 *哈希函数/散列函数* 来计算一个值在数组或桶(buckets)中或槽(slots)中对应的索引,可使用该索引找到所需的值。
|
哈希表使用 *哈希函数/散列函数* 来计算一个值在数组或桶(buckets)中或槽(slots)中对应的索引,可使用该索引找到所需的值。
|
||||||
@ -9,11 +9,15 @@
|
|||||||
以某种方式进行处理。
|
以某种方式进行处理。
|
||||||
|
|
||||||
|
|
||||||
![Hash Table](https://upload.wikimedia.org/wikipedia/commons/7/7d/Hash_table_3_1_1_0_1_0_0_SP.svg)
|
![Hash Table](./images/hash-table.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
通过单独的链接解决哈希冲突
|
通过单独的链接解决哈希冲突
|
||||||
|
|
||||||
![Hash Collision](https://upload.wikimedia.org/wikipedia/commons/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg)
|
![Hash Collision](./images/collision-resolution.jpeg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## 参考
|
## 参考
|
||||||
|
|
||||||
|
BIN
src/data-structures/hash-table/images/collision-resolution.jpeg
Normal file
BIN
src/data-structures/hash-table/images/collision-resolution.jpeg
Normal file
Binary file not shown.
After Width: | Height: | Size: 275 KiB |
BIN
src/data-structures/hash-table/images/hash-table.jpeg
Normal file
BIN
src/data-structures/hash-table/images/hash-table.jpeg
Normal file
Binary file not shown.
After Width: | Height: | Size: 165 KiB |
@ -3,32 +3,34 @@
|
|||||||
_Read this in other languages:_
|
_Read this in other languages:_
|
||||||
[_Português_](README.pt-BR.md)
|
[_Português_](README.pt-BR.md)
|
||||||
|
|
||||||
In computer science, **binary search trees** (BST), sometimes called
|
In computer science, **binary search trees** (BST), sometimes called
|
||||||
ordered or sorted binary trees, are a particular type of container:
|
ordered or sorted binary trees, are a particular type of container:
|
||||||
data structures that store "items" (such as numbers, names etc.)
|
data structures that store "items" (such as numbers, names etc.)
|
||||||
in memory. They allow fast lookup, addition and removal of
|
in memory. They allow fast lookup, addition and removal of
|
||||||
items, and can be used to implement either dynamic sets of
|
items, and can be used to implement either dynamic sets of
|
||||||
items, or lookup tables that allow finding an item by its key
|
items, or lookup tables that allow finding an item by its key
|
||||||
(e.g., finding the phone number of a person by name).
|
(e.g., finding the phone number of a person by name).
|
||||||
|
|
||||||
Binary search trees keep their keys in sorted order, so that lookup
|
Binary search trees keep their keys in sorted order, so that lookup
|
||||||
and other operations can use the principle of binary search:
|
and other operations can use the principle of binary search:
|
||||||
when looking for a key in a tree (or a place to insert a new key),
|
when looking for a key in a tree (or a place to insert a new key),
|
||||||
they traverse the tree from root to leaf, making comparisons to
|
they traverse the tree from root to leaf, making comparisons to
|
||||||
keys stored in the nodes of the tree and deciding, on the basis
|
keys stored in the nodes of the tree and deciding, on the basis
|
||||||
of the comparison, to continue searching in the left or right
|
of the comparison, to continue searching in the left or right
|
||||||
subtrees. On average, this means that each comparison allows
|
subtrees. On average, this means that each comparison allows
|
||||||
the operations to skip about half of the tree, so that each
|
the operations to skip about half of the tree, so that each
|
||||||
lookup, insertion or deletion takes time proportional to the
|
lookup, insertion or deletion takes time proportional to the
|
||||||
logarithm of the number of items stored in the tree. This is
|
logarithm of the number of items stored in the tree. This is
|
||||||
much better than the linear time required to find items by key
|
much better than the linear time required to find items by key
|
||||||
in an (unsorted) array, but slower than the corresponding
|
in an (unsorted) array, but slower than the corresponding
|
||||||
operations on hash tables.
|
operations on hash tables.
|
||||||
|
|
||||||
A binary search tree of size 9 and depth 3, with 8 at the root.
|
A binary search tree of size 9 and depth 3, with 8 at the root.
|
||||||
The leaves are not drawn.
|
The leaves are not drawn.
|
||||||
|
|
||||||
![Binary Search Tree](https://upload.wikimedia.org/wikipedia/commons/d/da/Binary_search_tree.svg)
|
![Trie](./images/binary-search-tree.jpg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Pseudocode for Basic Operations
|
## Pseudocode for Basic Operations
|
||||||
|
|
||||||
@ -45,7 +47,7 @@ insert(value)
|
|||||||
end if
|
end if
|
||||||
end insert
|
end insert
|
||||||
```
|
```
|
||||||
|
|
||||||
```text
|
```text
|
||||||
insertNode(current, value)
|
insertNode(current, value)
|
||||||
Pre: current is the node to start from
|
Pre: current is the node to start from
|
||||||
@ -84,8 +86,8 @@ contains(root, value)
|
|||||||
end if
|
end if
|
||||||
end contains
|
end contains
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Deletion
|
### Deletion
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -186,7 +188,7 @@ findNode(root, value)
|
|||||||
end if
|
end if
|
||||||
end findNode
|
end findNode
|
||||||
```
|
```
|
||||||
|
|
||||||
### Find Minimum
|
### Find Minimum
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -200,7 +202,7 @@ findMin(root)
|
|||||||
findMin(root.left)
|
findMin(root.left)
|
||||||
end findMin
|
end findMin
|
||||||
```
|
```
|
||||||
|
|
||||||
### Find Maximum
|
### Find Maximum
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -214,7 +216,7 @@ findMax(root)
|
|||||||
findMax(root.right)
|
findMax(root.right)
|
||||||
end findMax
|
end findMax
|
||||||
```
|
```
|
||||||
|
|
||||||
### Traversal
|
### Traversal
|
||||||
|
|
||||||
#### InOrder Traversal
|
#### InOrder Traversal
|
||||||
@ -244,7 +246,7 @@ preorder(root)
|
|||||||
end if
|
end if
|
||||||
end preorder
|
end preorder
|
||||||
```
|
```
|
||||||
|
|
||||||
#### PostOrder Traversal
|
#### PostOrder Traversal
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -258,7 +260,7 @@ postorder(root)
|
|||||||
end if
|
end if
|
||||||
end postorder
|
end postorder
|
||||||
```
|
```
|
||||||
|
|
||||||
## Complexities
|
## Complexities
|
||||||
|
|
||||||
### Time Complexity
|
### Time Complexity
|
||||||
|
@ -26,8 +26,9 @@ Uma pesquisa de árvore binária de tamanho 9 e profundidade 3, com valor 8
|
|||||||
na raíz.
|
na raíz.
|
||||||
As folhas não foram desenhadas.
|
As folhas não foram desenhadas.
|
||||||
|
|
||||||
|
![Trie](./images/binary-search-tree.jpg)
|
||||||
|
|
||||||
![Binary Search Tree](https://upload.wikimedia.org/wikipedia/commons/d/da/Binary_search_tree.svg)
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Pseudocódigo para Operações Básicas
|
## Pseudocódigo para Operações Básicas
|
||||||
|
|
||||||
@ -44,7 +45,7 @@ insert(value)
|
|||||||
end if
|
end if
|
||||||
end insert
|
end insert
|
||||||
```
|
```
|
||||||
|
|
||||||
```text
|
```text
|
||||||
insertNode(current, value)
|
insertNode(current, value)
|
||||||
Pre: current is the node to start from
|
Pre: current is the node to start from
|
||||||
@ -83,8 +84,8 @@ contains(root, value)
|
|||||||
end if
|
end if
|
||||||
end contains
|
end contains
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Remoção
|
### Remoção
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -185,7 +186,7 @@ findNode(root, value)
|
|||||||
end if
|
end if
|
||||||
end findNode
|
end findNode
|
||||||
```
|
```
|
||||||
|
|
||||||
### Encontrar Mínimo
|
### Encontrar Mínimo
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -199,7 +200,7 @@ findMin(root)
|
|||||||
findMin(root.left)
|
findMin(root.left)
|
||||||
end findMin
|
end findMin
|
||||||
```
|
```
|
||||||
|
|
||||||
### Encontrar Máximo
|
### Encontrar Máximo
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -213,7 +214,7 @@ findMax(root)
|
|||||||
findMax(root.right)
|
findMax(root.right)
|
||||||
end findMax
|
end findMax
|
||||||
```
|
```
|
||||||
|
|
||||||
### Traversal
|
### Traversal
|
||||||
|
|
||||||
#### Na Ordem Traversal (InOrder Traversal)
|
#### Na Ordem Traversal (InOrder Traversal)
|
||||||
@ -243,7 +244,7 @@ preorder(root)
|
|||||||
end if
|
end if
|
||||||
end preorder
|
end preorder
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Pós Ordem Traversal (PostOrder Traversal)
|
#### Pós Ordem Traversal (PostOrder Traversal)
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@ -257,7 +258,7 @@ postorder(root)
|
|||||||
end if
|
end if
|
||||||
end postorder
|
end postorder
|
||||||
```
|
```
|
||||||
|
|
||||||
## Complexidades
|
## Complexidades
|
||||||
|
|
||||||
### Complexidade de Tempo
|
### Complexidade de Tempo
|
||||||
|
Binary file not shown.
After Width: | Height: | Size: 146 KiB |
@ -5,22 +5,24 @@ _Read this in other languages:_
|
|||||||
[_Русский_](README.ru-RU.md),
|
[_Русский_](README.ru-RU.md),
|
||||||
[_Português_](README.pt-BR.md)
|
[_Português_](README.pt-BR.md)
|
||||||
|
|
||||||
In computer science, a **trie**, also called digital tree and sometimes
|
In computer science, a **trie**, also called digital tree and sometimes
|
||||||
radix tree or prefix tree (as they can be searched by prefixes),
|
radix tree or prefix tree (as they can be searched by prefixes),
|
||||||
is a kind of search tree—an ordered tree data structure that is
|
is a kind of search tree—an ordered tree data structure that is
|
||||||
used to store a dynamic set or associative array where the keys
|
used to store a dynamic set or associative array where the keys
|
||||||
are usually strings. Unlike a binary search tree, no node in the
|
are usually strings. Unlike a binary search tree, no node in the
|
||||||
tree stores the key associated with that node; instead, its
|
tree stores the key associated with that node; instead, its
|
||||||
position in the tree defines the key with which it is associated.
|
position in the tree defines the key with which it is associated.
|
||||||
All the descendants of a node have a common prefix of the string
|
All the descendants of a node have a common prefix of the string
|
||||||
associated with that node, and the root is associated with the
|
associated with that node, and the root is associated with the
|
||||||
empty string. Values are not necessarily associated with every
|
empty string. Values are not necessarily associated with every
|
||||||
node. Rather, values tend only to be associated with leaves,
|
node. Rather, values tend only to be associated with leaves,
|
||||||
and with some inner nodes that correspond to keys of interest.
|
and with some inner nodes that correspond to keys of interest.
|
||||||
For the space-optimized presentation of prefix tree, see compact
|
For the space-optimized presentation of prefix tree, see compact
|
||||||
prefix tree.
|
prefix tree.
|
||||||
|
|
||||||
![Trie](https://upload.wikimedia.org/wikipedia/commons/b/be/Trie_example.svg)
|
![Trie](./images/trie.jpg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
Na ciência da computação, uma **trie**, também chamada de árvore digital (digital tree)
|
Na ciência da computação, uma **trie**, também chamada de árvore digital (digital tree)
|
||||||
e algumas vezes de _radix tree_ ou _prefix tree_ (tendo em vista que eles
|
e algumas vezes de _radix tree_ ou _prefix tree_ (tendo em vista que eles
|
||||||
podem ser pesquisados por prefixos), é um tipo de árvore de pesquisa, uma
|
podem ser pesquisados por prefixos), é um tipo de árvore de pesquisa, uma
|
||||||
uma estrutura de dados de árvore ordenada que é usado para armazenar um
|
uma estrutura de dados de árvore ordenada que é usado para armazenar um
|
||||||
conjunto dinâmico ou matriz associativa onde as chaves são geralmente _strings_.
|
conjunto dinâmico ou matriz associativa onde as chaves são geralmente _strings_.
|
||||||
Ao contrário de uma árvore de pesquisa binária (binary search tree),
|
Ao contrário de uma árvore de pesquisa binária (binary search tree),
|
||||||
nenhum nó na árvore armazena a chave associada a esse nó; em vez disso,
|
nenhum nó na árvore armazena a chave associada a esse nó; em vez disso,
|
||||||
@ -17,7 +17,9 @@ internos que correspondem a chaves de interesse.
|
|||||||
Para a apresentação otimizada do espaço da árvore de prefixo (_prefix tree_),
|
Para a apresentação otimizada do espaço da árvore de prefixo (_prefix tree_),
|
||||||
veja árvore de prefixo compacto.
|
veja árvore de prefixo compacto.
|
||||||
|
|
||||||
![Trie](https://upload.wikimedia.org/wikipedia/commons/b/be/Trie_example.svg)
|
![Trie](./images/trie.jpg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## Referências
|
## Referências
|
||||||
|
|
||||||
|
@ -16,7 +16,9 @@
|
|||||||
дополнительную информацию, связанную с ключом, и обычно выделенными являются только листья и, возможно, некоторые
|
дополнительную информацию, связанную с ключом, и обычно выделенными являются только листья и, возможно, некоторые
|
||||||
внутренние узлы.
|
внутренние узлы.
|
||||||
|
|
||||||
![Префиксное дерево](https://upload.wikimedia.org/wikipedia/commons/b/be/Trie_example.svg)
|
![Префиксное дерево](./images/trie.jpg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
На рисунке представлено префиксное дерево, содержащее ключи «A», «to», «tea», «ted», «ten», «i», «in», «inn».
|
На рисунке представлено префиксное дерево, содержащее ключи «A», «to», «tea», «ted», «ten», «i», «in», «inn».
|
||||||
|
|
||||||
|
@ -2,13 +2,15 @@
|
|||||||
|
|
||||||
在计算机科学中, **字典树(trie,中文又被称为”单词查找树“或 ”键树“)**, 也称为数字树,有时候也被称为基数树或前缀树(因为它们可以通过前缀搜索),它是一种搜索树--一种已排序的数据结构,通常用于存储动态集或键为字符串的关联数组。
|
在计算机科学中, **字典树(trie,中文又被称为”单词查找树“或 ”键树“)**, 也称为数字树,有时候也被称为基数树或前缀树(因为它们可以通过前缀搜索),它是一种搜索树--一种已排序的数据结构,通常用于存储动态集或键为字符串的关联数组。
|
||||||
|
|
||||||
与二叉搜索树不同, 树上没有节点存储与该节点关联的键; 相反,节点在树上的位置定义了与之关联的键。一个节点的全部后代节点都有一个与该节点关联的通用的字符串前缀, 与根节点关联的是空字符串。
|
与二叉搜索树不同, 树上没有节点存储与该节点关联的键; 相反,节点在树上的位置定义了与之关联的键。一个节点的全部后代节点都有一个与该节点关联的通用的字符串前缀, 与根节点关联的是空字符串。
|
||||||
|
|
||||||
值对于字典树中关联的节点来说,不是必需的,相反,值往往和相关的叶子相关,以及与一些键相关的内部节点相关。
|
值对于字典树中关联的节点来说,不是必需的,相反,值往往和相关的叶子相关,以及与一些键相关的内部节点相关。
|
||||||
|
|
||||||
有关字典树的空间优化示意,请参阅紧凑前缀树
|
有关字典树的空间优化示意,请参阅紧凑前缀树
|
||||||
|
|
||||||
![Trie](https://upload.wikimedia.org/wikipedia/commons/b/be/Trie_example.svg)
|
![Trie](./images/trie.jpg)
|
||||||
|
|
||||||
|
*Made with [okso.app](https://okso.app)*
|
||||||
|
|
||||||
## 参考
|
## 参考
|
||||||
|
|
||||||
|
BIN
src/data-structures/trie/images/trie.jpg
Normal file
BIN
src/data-structures/trie/images/trie.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 143 KiB |
Loading…
Reference in New Issue
Block a user