1. Project Overview & Quickstart (trekhleb/javascript-algorithms)
File: README.md
JavaScript Algorithms and Data Structures
🇺🇦 UKRAINE IS BEING ATTACKED BY RUSSIAN ARMY. CIVILIANS ARE GETTING KILLED. RESIDENTIAL AREAS ARE GETTING BOMBED.
- Help Ukraine via:
- More info on war.ukraine.ua and MFA of Ukraine
This repository contains JavaScript based examples of many
popular algorithms and data structures.
Each algorithm and data structure has its own separate README
with related explanations and links for further reading (including ones
to YouTube videos).
Read this in other languages:
简体中文,
繁體中文,
한국어,
日本語,
Polski,
Français,
Español,
Português,
Русский,
Türkçe,
Italiano,
Bahasa Indonesia,
Українська,
Arabic,
Tiếng Việt,
Deutsch,
Uzbek,
עברית
Data Structures
A data structure is a particular way of organizing and storing data in a computer so that it can
be accessed and modified efficiently. More precisely, a data structure is a collection of data
values, the relationships among them, and the functions or operations that can be applied to
the data.
Remember that each data has its own trade-offs. And you need to pay attention more to why you're choosing a certain data structure than to how to implement it.
B - Beginner, A - Advanced
BLinked ListBDoubly Linked ListBQueueBStackBDeque - double-ended queueBHash TableBHeap - max and min heap versionsBPriority QueueATrieATreeABinary Search TreeAAVL TreeARed-Black TreeASegment Tree - with min/max/sum range queries examplesAFenwick Tree (Binary Indexed Tree)
AGraph (both directed and undirected)ADisjoint Set - a union–find data structure or merge–find setABloom FilterALRU Cache - Least Recently Used (LRU) cache
Algorithms
An algorithm is an unambiguous specification of how to solve a class of problems. It is
a set of rules that precisely define a sequence of operations.
B - Beginner, A - Advanced
Algorithms by Topic
- Math
BBit Manipulation - set/get/update/clear bits, multiplication/division by two, make negative etc.BBinary Floating Point - binary representation of the floating-point numbers.BFactorialBFibonacci Number - classic and closed-form versionsBPrime Factors - finding prime factors and counting them using Hardy-Ramanujan's theoremBPrimality Test (trial division method)BEuclidean Algorithm - calculate the Greatest Common Divisor (GCD)BLeast Common Multiple (LCM)BSieve of Eratosthenes - finding all prime numbers up to any given limitBIs Power of Two - check if the number is power of two (naive and bitwise algorithms)BPascal's TriangleBComplex Number - complex numbers and basic operations with themBRadian & Degree - radians to degree and backwards conversionBFast PoweringBHorner's method - polynomial evaluationBMatrices - matrices and basic matrix operations (multiplication, transposition, etc.)BEuclidean Distance - distance between two points/vectors/matricesAInteger PartitionASquare Root - Newton's methodALiu Hui π Algorithm - approximate π calculations based on N-gonsADiscrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up
- Sets
BCartesian Product - product of multiple setsBFisher–Yates Shuffle - random permutation of a finite sequenceAPower Set - all subsets of a set (bitwise, backtracking, and cascading solutions)APermutations (with and without repetitions)ACombinations (with and without repetitions)ALongest Common Subsequence (LCS)ALongest Increasing SubsequenceAShortest Common Supersequence (SCS)AKnapsack Problem - "0/1" and "Unbound" onesAMaximum Subarray - "Brute Force" and "Dynamic Programming" (Kadane's) versionsACombination Sum - find all combinations that form specific sum
- Strings
BHamming Distance - number of positions at which the symbols are differentBPalindrome - check if the string is the same in reverseALevenshtein Distance - minimum edit distance between two sequencesAKnuth–Morris–Pratt Algorithm (KMP Algorithm) - substring search (pattern matching)AZ Algorithm - substring search (pattern matching)ARabin Karp Algorithm - substring searchALongest Common SubstringARegular Expression Matching
- Searches
BLinear SearchBJump Search (or Block Search) - search in sorted arrayBBinary Search - search in sorted arrayBInterpolation Search - search in uniformly distributed sorted array
- Sorting
BBubble SortBSelection SortBInsertion SortBHeap SortBMerge SortBQuicksort - in-place and non-in-place implementationsBShellsortBCounting SortBRadix SortBBucket Sort
- Linked Lists
- Trees
BDepth-First Search (DFS)BBreadth-First Search (BFS)
- Graphs
BDepth-First Search (DFS)BBreadth-First Search (BFS)BKruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graphADijkstra Algorithm - finding the shortest paths to all graph vertices from single vertexABellman-Ford Algorithm - finding the shortest paths to all graph vertices from single vertexAFloyd-Warshall Algorithm - find the shortest paths between all pairs of verticesADetect Cycle - for both directed and undirected graphs (DFS and Disjoint Set based versions)APrim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graphATopological Sorting - DFS methodAArticulation Points - Tarjan's algorithm (DFS based)ABridges - DFS based algorithmAEulerian Path and Eulerian Circuit - Fleury's algorithm - Visit every edge exactly onceAHamiltonian Cycle - Visit every vertex exactly onceAStrongly Connected Components - Kosaraju's algorithmATravelling Salesman Problem - shortest possible route that visits each city and returns to the origin city
- Cryptography
BPolynomial Hash - rolling hash function based on polynomialBRail Fence Cipher - a transposition cipher algorithm for encoding messagesBCaesar Cipher - simple substitution cipherBHill Cipher - substitution cipher based on linear algebra
- Machine Learning
BNanoNeuron - 7 simple JS functions that illustrate how machines can actually learn (forward/backward propagation)Bk-NN - k-nearest neighbors classification algorithmBk-Means - k-Means clustering algorithm
- Image Processing
BSeam Carving - content-aware image resizing algorithm
- Statistics
BWeighted Random - select the random item from the list based on items' weights
- Evolutionary algorithms
AGenetic algorithm - example of how the genetic algorithm may be applied for training the self-parking cars
- Uncategorized
BTower of HanoiBSquare Matrix Rotation - in-place algorithmBJump Game - backtracking, dynamic programming (top-down + bottom-up) and greedy examplesBUnique Paths - backtracking, dynamic programming and Pascal's Triangle based examplesBRain Terraces - trapping rain water problem (dynamic programming and brute force versions)BRecursive Staircase - count the number of ways to reach to the top (4 solutions)BBest Time To Buy Sell Stocks - divide and conquer and one-pass examplesBValid Parentheses - check if a string has valid parentheses (using stack)AN-Queens ProblemAKnight's Tour
Algorithms by Paradigm
An algorithmic paradigm is a generic method or approach which underlies the design of a class
of algorithms. It is an abstraction higher than the notion of an algorithm, just as an
algorithm is an abstraction higher than a computer program.
- Brute Force - look at all the possibilities and selects the best solution
BLinear SearchBRain Terraces - trapping rain water problemBRecursive Staircase - count the number of ways to reach the topAMaximum SubarrayATravelling Salesman Problem - shortest possible route that visits each city and returns to the origin cityADiscrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up
- Greedy - choose the best option at the current time, without any consideration for the future
BJump GameAUnbound Knapsack ProblemADijkstra Algorithm - finding the shortest path to all graph verticesAPrim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graphAKruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph
- Divide and Conquer - divide the problem into smaller parts and then solve those parts
BBinary SearchBTower of HanoiBPascal's TriangleBEuclidean Algorithm - calculate the Greatest Common Divisor (GCD)BMerge SortBQuicksortBTree Depth-First Search (DFS)BGraph Depth-First Search (DFS)BMatrices - generating and traversing the matrices of different shapesBJump GameBFast PoweringBBest Time To Buy Sell Stocks - divide and conquer and one-pass examplesAPermutations (with and without repetitions)ACombinations (with and without repetitions)AMaximum Subarray
- Dynamic Programming - build up a solution using previously found sub-solutions
BFibonacci NumberBJump GameBUnique PathsBRain Terraces - trapping rain water problemBRecursive Staircase - count the number of ways to reach the topBSeam Carving - content-aware image resizing algorithmALevenshtein Distance - minimum edit distance between two sequencesALongest Common Subsequence (LCS)ALongest Common SubstringALongest Increasing SubsequenceAShortest Common SupersequenceA0/1 Knapsack ProblemAInteger PartitionAMaximum SubarrayABellman-Ford Algorithm - finding the shortest path to all graph verticesAFloyd-Warshall Algorithm - find the shortest paths between all pairs of verticesARegular Expression Matching
- Backtracking - similarly to brute force, try to generate all possible solutions, but each time you generate the next solution, you test
if it satisfies all conditions and only then continue generating subsequent solutions. Otherwise, backtrack and go on a
different path to finding a solution. Normally the DFS traversal of state-space is being used.BJump GameBUnique PathsBPower Set - all subsets of a setAHamiltonian Cycle - Visit every vertex exactly onceAN-Queens ProblemAKnight's TourACombination Sum - find all combinations that form specific sum
- Branch & Bound - remember the lowest-cost solution found at each stage of the backtracking
search, and use the cost of the lowest-cost solution found so far as a lower bound on the cost of
a least-cost solution to the problem in order to discard partial solutions with costs larger than the
lowest-cost solution found so far. Normally, BFS traversal in combination with DFS traversal of state-space
tree is being used.
How to use this repository
Install all dependencies
npm installRun ESLint
You may want to run it to check code quality.
npm run lintRun all tests
npm testRun tests by name
npm test -- 'LinkedList'Troubleshooting
If linting or testing is failing, try to delete the node_modules folder and re-install npm packages:
rm -rf ./node_modules
npm iAlso, make sure that you're using the correct Node version (>=16). If you're using nvm for Node version management you may run nvm use from the root folder of the project and the correct version will be picked up.
Playground
You may play with data-structures and algorithms in ./src/playground/playground.js file and write
tests for it in ./src/playground/__test__/playground.test.js.
Then just, simply run the following command to test if your playground code works as expected:
npm test -- 'playground'Useful Information
References
Big O Notation
Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.
On the chart below, you may find the most common orders of growth of algorithms specified in Big O notation.
Source: Big O Cheat Sheet.
Below is the list of some of the most used Big O notations and their performance comparisons against different sizes of the input data.
| Big O Notation | Type | Computations for 10 elements | Computations for 100 elements | Computations for 1000 elements |
|---|---|---|---|---|
| O(1) | Constant | 1 | 1 | 1 |
| O(log N) | Logarithmic | 3 | 6 | 9 |
| O(N) | Linear | 10 | 100 | 1000 |
| O(N log N) | n log(n) | 30 | 600 | 9000 |
| O(N^2) | Quadratic | 100 | 10000 | 1000000 |
| O(2^N) | Exponential | 1024 | 1.26e+29 | 1.07e+301 |
| O(N!) | Factorial | 3628800 | 9.3e+157 | 4.02e+2567 |
Data Structure Operations Complexity
| Data Structure | Access | Search | Insertion | Deletion | Comments |
|---|---|---|---|---|---|
| Array | 1 | n | n | n | |
| Stack | n | n | 1 | 1 | |
| Queue | n | n | 1 | 1 | |
| Linked List | n | n | 1 | n | |
| Hash Table | - | n | n | n | In case of perfect hash function costs would be O(1) |
| Binary Search Tree | n | n | n | n | In case of balanced tree costs would be O(log(n)) |
| B-Tree | log(n) | log(n) | log(n) | log(n) | |
| Red-Black Tree | log(n) | log(n) | log(n) | log(n) | |
| AVL Tree | log(n) | log(n) | log(n) | log(n) | |
| Bloom Filter | - | 1 | 1 | - | False positives are possible while searching |
Array Sorting Algorithms Complexity
| Name | Best | Average | Worst | Memory | Stable | Comments |
|---|---|---|---|---|---|---|
| Bubble sort | n | n2 | n2 | 1 | Yes | |
| Insertion sort | n | n2 | n2 | 1 | Yes | |
| Selection sort | n2 | n2 | n2 | 1 | No | |
| Heap sort | n log(n) | n log(n) | n log(n) | 1 | No | |
| Merge sort | n log(n) | n log(n) | n log(n) | n | Yes | |
| Quick sort | n log(n) | n log(n) | n2 | log(n) | No | Quicksort is usually done in-place with O(log(n)) stack space |
| Shell sort | n log(n) | depends on gap sequence | n (log(n))2 | 1 | No | |
| Counting sort | n + r | n + r | n + r | n + r | Yes | r - biggest number in array |
| Radix sort | n * k | n * k | n * k | n + k | Yes | k - length of longest key |
Author
A few more projects and articles about JavaScript and algorithms on trekhleb.dev:
- 🧠 yesbrainer.ai – council of AI models for the decisions that aren’t no-brainers (BYOK, private, no account)
- ✍🏻 okso.app – drawing app to express, grasp, and organize your thoughts and ideas
File: src/playground/README.md
Playground
You may use playground.js file to play with data
structures and algorithms. The code from playground.js may
be tested in ./__test__/playground.test.js file.
To run tests simply run:
npm test -- -t 'playground'File: src/data-structures/trie/README.ko-KO.md
Trie
Read this in other languages:
简体中文,
Русский,
Português,
Українська,
한국어
컴퓨터 과학에서 트라이는 디지털 트리라고도 불리며 때로는 기수 트리 또는 접두사 트리(접두사로 검색할 수 있기 때문에)라고도 불리며 일종의 검색 트리입니다. 키가 보통 문자열인 동적 집합 또는 연관 배열을 저장하는 데 사용되는 순서가 지정된 트리 데이터 구조입니다. 이진 검색 트리와 달리 트리의 어떤 노드도 해당 노드와 연결된 키를 저장하지 않으며 대신 트리의 위치가 해당 노드와 연결된 키를 정의합니다. 노드의 모든 하위 항목은 해당 노드와 연결된 문자열의 공통 접두사를 가지며 루트는 빈 문자열과 연결됩니다. 값은 모든 노드와 반드시 연결되지는 않습니다. 오히려 값은 나뭇잎과 관심 있는 키에 해당하는 일부 내부 노드에만 연결되는 경향이 있습니다. 접두사 트리의 공간에 최적화된 표현은 콤팩트 접두사 트리를 참조하십시오.
Made with okso.app
참조
File: src/data-structures/trie/README.md
Trie
Read this in other languages:
简体中文,
Русский,
Português,
Українська,
한국어
In computer science, a trie, also called digital tree and sometimes
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
used to store a dynamic set or associative array where the keys
are usually strings. Unlike a binary search tree, no node in the
tree stores the key associated with that node; instead, its
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
associated with that node, and the root is associated with the
empty string. Values are not necessarily associated with every
node. Rather, values tend only to be associated with leaves,
and with some inner nodes that correspond to keys of interest.
For the space-optimized presentation of prefix tree, see compact
prefix tree.
Made with okso.app
References
File: src/data-structures/trie/README.pt-BR.md
Árvore de Prefixos (Trie)
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
podem ser pesquisados por prefixos), é um tipo de árvore de pesquisa, 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.
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,
sua posição na árvore define a chave com a qual ela está associada.
Todos os descendentes de um nó possuem em comum o prefixo de uma string
associada com aquele nó, e a raiz é associada com uma string vazia.
Valores não são necessariamente associados a todos nós. Em vez disso,
os valores tendem a ser associados apenas a folhas e com alguns nós
internos que correspondem a chaves de interesse.
Para a apresentação otimizada do espaço da árvore de prefixo (prefix tree),
veja árvore de prefixo compacto.
Made with okso.app
Referências
File: src/data-structures/trie/README.ru-RU.md
Префиксное дерево
Префиксное дерево (также бор, луч, нагруженное или суффиксное дерево) в информатике - упорядоченная древовидная
структура данных, которая используется для хранения динамических множеств или ассоциативных массивов, где
ключом обычно выступают строки. Дерево называется префиксным, потому что поиск осуществляется по префиксам.
В отличие от бинарного дерева, узлы не содержат ключи, соответствующие узлу. Представляет собой корневое дерево, каждое
ребро которого помечено каким-то символом так, что для любого узла все рёбра, соединяющие этот узел с его сыновьями,
помечены разными символами. Некоторые узлы префиксного дерева выделены (на рисунке они подписаны цифрами) и считается,
что префиксное дерево содержит данную строку-ключ тогда и только тогда, когда эту строку можно прочитать на пути из
корня до некоторого выделенного узла.
Таким образом, в отличие от бинарных деревьев поиска, ключ, идентифицирующий конкретный узел дерева, не явно хранится в
данном узле, а неявно задаётся положением данного узла в дереве. Получить ключ можно выписыванием подряд символов,
помечающих рёбра на пути от корня до узла. Ключ корня дерева — пустая строка. Часто в выделенных узлах хранят
дополнительную информацию, связанную с ключом, и обычно выделенными являются только листья и, возможно, некоторые
внутренние узлы.
Made with okso.app
На рисунке представлено префиксное дерево, содержащее ключи «A», «to», «tea», «ted», «ten», «i», «in», «inn».
Ссылки
File: src/data-structures/trie/README.uk-UA.md
Префіксне дерево
Префіксне дерево (Також промінь, навантажене або суфіксне дерево) в інформатиці - впорядкована деревоподібна
структура даних, яка використовується для зберігання динамічних множин або асоціативних масивів, де
ключем зазвичай виступають рядки. Дерево називається префіксним, тому що пошук здійснюється за префіксами.
На відміну від бінарного дерева, вузли не містять ключів, що відповідають вузлу. Являє собою кореневе дерево, кожне
ребро якого позначено якимось символом так, що для будь-якого вузла всі ребра, що з'єднують цей вузол з його синами,
позначені різними символами. Деякі вузли префіксного дерева виділені (на малюнку вони підписані цифрами) і вважається,
що префіксне дерево містить цей рядок-ключ тоді і тільки тоді, коли цей рядок можна прочитати на шляху з
кореня до певного виділеного вузла.
Таким чином, на відміну від бінарних дерев пошуку, ключ, що ідентифікує конкретний вузол дерева, не явно зберігається в
цьому вузлі, а неявно задається положенням цього вузла в дереві. Отримати ключ можна виписуванням поспіль символів,
помічають ребра по дорозі від кореня до вузла. Ключ кореня дерева - порожній рядок. Часто у виділених вузлах зберігають
додаткову інформацію, пов'язану з ключем, і зазвичай виділеними є тільки листя і, можливо, деякі
внутрішні вузли.
Made with okso.app
На малюнку представлено префіксне дерево, що містить ключі. «A», «to», «tea», «ted», «ten», «i», «in», «inn».
Посилання
File: src/data-structures/trie/README.zh-CN.md
字典树
在计算机科学中, 字典树(trie,中文又被称为”单词查找树“或 ”键树“), 也称为数字树,有时候也被称为基数树或前缀树(因为它们可以通过前缀搜索),它是一种搜索树--一种已排序的数据结构,通常用于存储动态集或键为字符串的关联数组。
与二叉搜索树不同, 树上没有节点存储与该节点关联的键; 相反,节点在树上的位置定义了与之关联的键。一个节点的全部后代节点都有一个与该节点关联的通用的字符串前缀, 与根节点关联的是空字符串。
值对于字典树中关联的节点来说,不是必需的,相反,值往往和相关的叶子相关,以及与一些键相关的内部节点相关。
有关字典树的空间优化示意,请参阅紧凑前缀树
Made with okso.app
参考
File: src/data-structures/tree/binary-search-tree/README.md
Binary Search Tree
Read this in other languages:
Português
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.)
in memory. They allow fast lookup, addition and removal of
items, and can be used to implement either dynamic sets of
items, or lookup tables that allow finding an item by its key
(e.g., finding the phone number of a person by name).
Binary search trees keep their keys in sorted order, so that lookup
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),
they traverse the tree from root to leaf, making comparisons to
keys stored in the nodes of the tree and deciding, on the basis
of the comparison, to continue searching in the left or right
subtrees. On average, this means that each comparison allows
the operations to skip about half of the tree, so that each
lookup, insertion or deletion takes time proportional to the
logarithm of the number of items stored in the tree. This is
much better than the linear time required to find items by key
in an (unsorted) array, but slower than the corresponding
operations on hash tables.
A binary search tree of size 9 and depth 3, with 8 at the root.
The leaves are not drawn.
Made with okso.app
Pseudocode for Basic Operations
Insertion
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 insertinsertNode(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 insertNodeSearching
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 containsDeletion
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 removeFind Parent of Node
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 findParentFind Node
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 findNodeFind Minimum
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 findMinFind Maximum
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 findMaxTraversal
InOrder Traversal
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 inorderPreOrder Traversal
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 preorderPostOrder Traversal
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 postorderComplexities
Time Complexity
| Access | Search | Insertion | Deletion |
|---|---|---|---|
| O(log(n)) | O(log(n)) | O(log(n)) | O(log(n)) |
Space Complexity
O(n)
References
File: src/data-structures/tree/binary-search-tree/README.pt-BR.md
Árvore de Pesquisa Binária (Binary Search Tree)
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.
Made with okso.app
Pseudocódigo para Operações Básicas
Inserção
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 insertinsertNode(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 insertNodePesquisa
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 containsRemoção
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 removeEncontrar o Nó Pai
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 findParentEncontrar um Nó
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 findNodeEncontrar Mínimo
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 findMinEncontrar Máximo
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 findMaxTraversal
Na Ordem Traversal (InOrder Traversal)
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 inorderPré Ordem Traversal (PreOrder Traversal)
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 preorderPós Ordem Traversal (PostOrder Traversal)
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 postorderComplexidades
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
2. Official Technical Reference & Guides (trekhleb/trekhleb.github.io)
trekhleb.dev
My personal website with a list of my projects that help people learn and blog posts about life, web-development, and machine-learning.
Development
The website is built on Gatsby. See the Gatsby cheat-sheet for development hints.
Running the project locally
Install proper version of Node:
nvm useInstall dependencies:
npm iTo run the project locally in development mode on http://localhost:8000:
npm run developView GraphiQL, an in-browser IDE, to explore your site's data and schema on http://localhost:8000/___graphql
To build the production version of the project:
npm run buildServe the production build for testing on http://localhost:9000:
npm run serveTo do ESLint and Type checking:
npm run lint
npm run typeTo fix the Lint errors run:
npm run lint -- --fixWorking with icons
Use react-icons.github.io to search for available icons.
Styling components
Use tailwindcss.com to search for available CSS classes.
Custom Domain Support
To serve the trekhleb.github.io web-site on a custom domain trekhleb.dev make sure that the public branch has CNAME file in the root folder. For more details read this.