Compare commits

...

13 Commits

Author SHA1 Message Date
Yuteng Lin
15186aeb6b
Merge 2a95643bf5 into ca3d16dcce 2024-07-17 10:42:14 +09:00
Vlad Sosnov
ca3d16dcce
Update README.uk-UA.md (#991)
Co-authored-by: Oleksii Trekhleb <3000285+trekhleb@users.noreply.github.com>
2024-07-13 21:28:34 +02:00
Vicente Gutiérrez
e7f30a7bf7
Fix typos README.es-ES for linked list (#850) 2024-07-13 21:28:02 +02:00
Enzo
471e6d0791
Add es-ES translation to search/binary-search (#893) 2024-07-13 21:27:09 +02:00
Alaz Tetik
351a63a59f
Update README.md by correcting Turkish lang name (#904)
Co-authored-by: Oleksii Trekhleb <3000285+trekhleb@users.noreply.github.com>
2024-07-13 21:25:58 +02:00
Nikita Gurskiy
0e2b2574f8
update the ES README a lenguage correction (#952) 2024-07-13 21:23:02 +02:00
Youssef Rabei
0c054f782a
Update README.ar-AR.md (#959)
Co-authored-by: Oleksii Trekhleb <3000285+trekhleb@users.noreply.github.com>
2024-07-13 21:22:10 +02:00
Yuteng Lin
2a95643bf5
Merge branch 'master' into binary-search-tree-translation-zh-cn 2022-09-28 15:49:18 +08:00
Yuteng Lin
7da59626f1
Merge branch 'master' into binary-search-tree-translation-zh-cn 2022-09-01 14:26:58 +08:00
Yuteng Lin
3b422e95df
Merge branch 'master' into binary-search-tree-translation-zh-cn 2022-08-29 11:03:20 +08:00
Yuteng Lin
c09412d8b6
Merge branch 'master' into binary-search-tree-translation-zh-cn 2022-08-26 13:45:42 +08:00
yuteng lin
51699930c5 Update README.zh-CN.md 2022-08-26 11:14:57 +08:00
yuteng lin
baf315e449 Translation
Translation of binary search tree
2022-08-26 10:47:49 +08:00
10 changed files with 328 additions and 32 deletions

View File

@ -3,7 +3,7 @@
[![Build Status](https://travis-ci.org/trekhleb/javascript-algorithms.svg?branch=master)](https://travis-ci.org/trekhleb/javascript-algorithms) [![Build Status](https://travis-ci.org/trekhleb/javascript-algorithms.svg?branch=master)](https://travis-ci.org/trekhleb/javascript-algorithms)
[![codecov](https://codecov.io/gh/trekhleb/javascript-algorithms/branch/master/graph/badge.svg)](https://codecov.io/gh/trekhleb/javascript-algorithms) [![codecov](https://codecov.io/gh/trekhleb/javascript-algorithms/branch/master/graph/badge.svg)](https://codecov.io/gh/trekhleb/javascript-algorithms)
تحتوي هذا مقالة على أمثلة عديدة تستند إلى الخوارزميات الشائعة وهياكل البيانات في الجافا سكريبت. تحتوي هذه المقالة على أمثلة عديدة تستند إلى الخوارزميات الشائعة وهياكل البيانات في الجافا سكريبت.
كل خوارزمية وهياكل البيانات لها برنامج README منفصل خاص بها كل خوارزمية وهياكل البيانات لها برنامج README منفصل خاص بها
مع التفسيرات والروابط ذات الصلة لمزيد من القراءة (بما في ذلك تلك مع التفسيرات والروابط ذات الصلة لمزيد من القراءة (بما في ذلك تلك

View File

@ -70,7 +70,7 @@ definen con precisión una secuencia de operaciones.
* **Matemáticas** * **Matemáticas**
* `P` [Manipulación de bits](src/algorithms/math/bits) - asignar/obtener/actualizar/limpiar bits, multiplicación/división por dos, hacer negativo, etc. * `P` [Manipulación de bits](src/algorithms/math/bits) - asignar/obtener/actualizar/limpiar bits, multiplicación/división por dos, hacer negativo, etc.
* `P` [Factorial](src/algorithms/math/factorial) * `P` [Factorial](src/algorithms/math/factorial)
* `P` [Número de Fibonacci](src/algorithms/math/fibonacci) * `P` [Sucesión de Fibonacci](src/algorithms/math/fibonacci)
* `P` [Prueba de primalidad](src/algorithms/math/primality-test) (método de división de prueba) * `P` [Prueba de primalidad](src/algorithms/math/primality-test) (método de división de prueba)
* `P` [Algoritmo de Euclides](src/algorithms/math/euclidean-algorithm) - calcular el Máximo común divisor (MCD) * `P` [Algoritmo de Euclides](src/algorithms/math/euclidean-algorithm) - calcular el Máximo común divisor (MCD)
* `P` [Mínimo común múltiplo](src/algorithms/math/least-common-multiple) (MCM) * `P` [Mínimo común múltiplo](src/algorithms/math/least-common-multiple) (MCM)

View File

@ -0,0 +1,27 @@
# Búsqueda binaria
_Lea esto en otros idiomas:_
[English](README.md)
[Português brasileiro](README.pt-BR.md).
En informática, la búsqueda binaria, también conocida como búsqueda de medio intervalo
búsqueda, búsqueda logarítmica, o corte binario, es un algoritmo de búsqueda
que encuentra la posición de un valor objetivo dentro de una matriz
ordenada. La búsqueda binaria compara el valor objetivo con el elemento central
de la matriz; si son desiguales, se elimina la mitad en la que
la mitad en la que no puede estar el objetivo se elimina y la búsqueda continúa
en la mitad restante hasta que tenga éxito. Si la búsqueda
termina con la mitad restante vacía, el objetivo no está
en la matriz.
![Búsqueda binaria](https://upload.wikimedia.org/wikipedia/commons/8/83/Binary_Search_Depiction.svg)
## Complejidad
**Complejidad de tiempo**: `O(log(n))` - ya que dividimos el área de búsqueda en dos para cada
siguiente iteración.
## Referencias
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm)
- [YouTube](https://www.youtube.com/watch?v=P3YID7liBug&index=29&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

View File

@ -2,6 +2,7 @@
_Read this in other languages:_ _Read this in other languages:_
[Português brasileiro](README.pt-BR.md). [Português brasileiro](README.pt-BR.md).
[Español](README.es-ES.md).
In computer science, binary search, also known as half-interval In computer science, binary search, also known as half-interval
search, logarithmic search, or binary chop, is a search algorithm search, logarithmic search, or binary chop, is a search algorithm

View File

@ -2,6 +2,7 @@
_Leia isso em outras línguas:_ _Leia isso em outras línguas:_
[english](README.md). [english](README.md).
[Español](README.es-ES.md).
Em ciência da computação, busca binária, também conhecida como busca de meio-intervalo, busca logarítmica ou corte binário, é um algoritmo de pesquisa Em ciência da computação, busca binária, também conhecida como busca de meio-intervalo, busca logarítmica ou corte binário, é um algoritmo de pesquisa
que encontra a posição de um elemento alvo dentro de um que encontra a posição de um elemento alvo dentro de um

View File

@ -7,9 +7,9 @@ _Lee este artículo en otros idiomas:_
[_Português_](README.pt-BR.md) [_Português_](README.pt-BR.md)
[_English_](README.md) [_English_](README.md)
En ciencias de la computaciòn una **lista enlazada** es una coleccion linear En ciencias de la computación una **lista enlazada** es una colección lineal
de elementos de datos, en los cuales el orden linear no es dado por de elementos, en los cuales el orden lineal no es dado por
su posciòn fisica en memoria. En cambio, cada su posición física en memoria. En cambio, cada
elemento señala al siguiente. Es una estructura de datos elemento señala al siguiente. Es una estructura de datos
que consiste en un grupo de nodos los cuales juntos representan que consiste en un grupo de nodos los cuales juntos representan
una secuencia. En su forma más sencilla, cada nodo está una secuencia. En su forma más sencilla, cada nodo está
@ -19,10 +19,10 @@ permite la inserción o eliminación de elementos
desde cualquier posición en la secuencia durante la iteración. desde cualquier posición en la secuencia durante la iteración.
Las variantes más complejas agregan enlaces adicionales, permitiendo Las variantes más complejas agregan enlaces adicionales, permitiendo
una eficiente inserción o eliminación desde referencias arbitrarias una eficiente inserción o eliminación desde referencias arbitrarias
del elemento. Una desventaja de las listas lazadas es que el tiempo de del elemento. Una desventaja de las listas enlazadas es que el tiempo de
acceso es lineal (y difícil de canalizar). Un acceso acceso es lineal (y difícil de canalizar). Un acceso
más rápido, como un acceso aleatorio, no es factible. Los arreglos más rápido, como un acceso aleatorio, no es factible. Los arreglos
tienen una mejor locazion en caché comparados con las listas lazadas. tienen una mejor localización en caché comparados con las listas enlazadas.
![Linked List](./images/linked-list.jpeg) ![Linked List](./images/linked-list.jpeg)
@ -112,7 +112,7 @@ Remove(head, value)
end Remove end Remove
``` ```
### Atrevesar ### Atravesar
```text ```text
Traverse(head) Traverse(head)

View File

@ -10,8 +10,8 @@
Додаткова операція для читання головного елемента (peek) дає доступ Додаткова операція для читання головного елемента (peek) дає доступ
до останнього елементу стека без зміни самого стека. до останнього елементу стека без зміни самого стека.
Найчастіше принцип роботи стека порівнюють зі чаркою тарілок: щоб узяти другу Найчастіше принцип роботи стека порівнюють із стопкою тарілок: щоб узяти другу
зверху потрібно зняти верхню. зверху потрібно спочатку зняти верхню.
Ілюстрація роботи зі стеком. Ілюстрація роботи зі стеком.

View File

@ -1,10 +1,10 @@
# 树 # 树
* [二叉搜索树](binary-search-tree) - [二叉搜索树](binary-search-tree/README.zh-CN.md)
* [AVL树](avl-tree) - [AVL 树](avl-tree)
* [红黑树](red-black-tree) - [红黑树](red-black-tree)
* [线段树](segment-tree) - with min/max/sum range queries examples - [线段树](segment-tree) - with min/max/sum range queries examples
* [芬威克树/Fenwick Tree](fenwick-tree) (Binary Indexed Tree) - [芬威克树/Fenwick Tree](fenwick-tree) (Binary Indexed Tree)
在计算机科学中, **树(tree)** 是一种广泛使用的抽象数据类型(ADT)— 或实现此 ADT 的数据结构 — 模拟分层树结构, 具有根节点和有父节点的子树,表示为一组链接节点。 在计算机科学中, **树(tree)** 是一种广泛使用的抽象数据类型(ADT)— 或实现此 ADT 的数据结构 — 模拟分层树结构, 具有根节点和有父节点的子树,表示为一组链接节点。
@ -18,9 +18,9 @@
![Tree](./images/tree.jpeg) ![Tree](./images/tree.jpeg)
*Made with [okso.app](https://okso.app)* _Made with [okso.app](https://okso.app)_
## 参考 ## 参考
- [Wikipedia](https://en.wikipedia.org/wiki/Tree_(data_structure)) - [Wikipedia](<https://en.wikipedia.org/wiki/Tree_(data_structure)>)
- [YouTube](https://www.youtube.com/watch?v=oSWTXtMglKE&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=8) - [YouTube](https://www.youtube.com/watch?v=oSWTXtMglKE&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=8)

View File

@ -1,7 +1,7 @@
# Binary Search Tree # Binary Search Tree
_Read this in other languages:_ _Read this in other languages:_
[_Português_](README.pt-BR.md) [_Português_](README.pt-BR.md),[_简体中文_](README.zh-CN.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:
@ -30,7 +30,7 @@ The leaves are not drawn.
![Trie](./images/binary-search-tree.jpg) ![Trie](./images/binary-search-tree.jpg)
*Made with [okso.app](https://okso.app)* _Made with [okso.app](https://okso.app)_
## Pseudocode for Basic Operations ## Pseudocode for Basic Operations
@ -87,7 +87,6 @@ contains(root, value)
end contains end contains
``` ```
### Deletion ### Deletion
```text ```text

View File

@ -0,0 +1,268 @@
# 二叉搜索树
_Read this in other languages:_
[_Português_](README.pt-BR.md),[_English_](README.md)
在计算机科学中, **二叉搜索树** (BST), 也称为有序二叉树或排序二叉树, 是一种特殊的容器:
在内存中存储“元素”的数据结构(如数字,名称等)。二叉搜索树可以快速查找,添加和删除元素,也可用于
构建动态元素集或在表中根据键查找元素值 (例:通过某人姓名找到某人的手机号)。
二叉搜索树为有序序列,所以在进行查找或其他操作时可以使用二分查找原理:
在树中寻找键(或插入新键的位置)时,查找过程为: 从根到叶遍历树,通过比较
存储在树的节点中的键来判断继续向左或向右搜索子树。 平均而言,这意味着每次
比较都允许跳过大约一半的操作,这样每个查找、插入或删除所花费的时间为
树中存储的项目数的对数。 这是比按键在(未排序的)数组中查找元素所需的
线性时间要好得多,但比在哈希表中相应的操作慢。
下图为一个大小为 9深度为 38 为根结点的二叉搜索树。
叶子节点没有被绘制。
![Trie](./images/binary-search-tree.jpg)
_Made with [okso.app](https://okso.app)_
## 基础操作的伪代码
### 插入
```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
```
### 查找
```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
```
### 删除
```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
```
### 查找某个节点的父节点
```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
```
### 查找节点
```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
```
### 查找最小值
```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
```
### 查找最大值
```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
```
### 遍历
#### 中序遍历
```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
```
#### 前序遍历
```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
```
#### 后序遍历
```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
```
## 复杂度
### 时间复杂度
| Access | Search | Insertion | Deletion |
| :-------: | :-------: | :-------: | :-------: |
| O(log(n)) | O(log(n)) | O(log(n)) | O(log(n)) |
### 空间复杂度
O(n)
## 参考资料
- [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)