Skip to content

Commit ab15821

Browse files
committed
小傅哥 | update
1 parent acbca45 commit ab15821

File tree

149 files changed

+9123
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

149 files changed

+9123
-0
lines changed
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
# Binary Search Tree
2+
3+
In computer science, **binary search trees** (BST), sometimes called
4+
ordered or sorted binary trees, are a particular type of container:
5+
data structures that store "items" (such as numbers, names etc.)
6+
in memory. They allow fast lookup, addition and removal of
7+
items, and can be used to implement either dynamic sets of
8+
items, or lookup tables that allow finding an item by its key
9+
(e.g., finding the phone number of a person by name).
10+
11+
Binary search trees keep their keys in sorted order, so that lookup
12+
and other operations can use the principle of binary search:
13+
when looking for a key in a tree (or a place to insert a new key),
14+
they traverse the tree from root to leaf, making comparisons to
15+
keys stored in the nodes of the tree and deciding, on the basis
16+
of the comparison, to continue searching in the left or right
17+
subtrees. On average, this means that each comparison allows
18+
the operations to skip about half of the tree, so that each
19+
lookup, insertion or deletion takes time proportional to the
20+
logarithm of the number of items stored in the tree. This is
21+
much better than the linear time required to find items by key
22+
in an (unsorted) array, but slower than the corresponding
23+
operations on hash tables.
24+
25+
A binary search tree of size 9 and depth 3, with 8 at the root.
26+
The leaves are not drawn.
27+
28+
![Binary Search Tree](https://upload.wikimedia.org/wikipedia/commons/d/da/Binary_search_tree.svg)
29+
30+
## Pseudocode for Basic Operations
31+
32+
### Insertion
33+
34+
```text
35+
insert(value)
36+
Pre: value has passed custom type checks for type T
37+
Post: value has been placed in the correct location in the tree
38+
if root = ø
39+
root ← node(value)
40+
else
41+
insertNode(root, value)
42+
end if
43+
end insert
44+
```
45+
46+
```text
47+
insertNode(current, value)
48+
Pre: current is the node to start from
49+
Post: value has been placed in the correct location in the tree
50+
if value < current.value
51+
if current.left = ø
52+
current.left ← node(value)
53+
else
54+
InsertNode(current.left, value)
55+
end if
56+
else
57+
if current.right = ø
58+
current.right ← node(value)
59+
else
60+
InsertNode(current.right, value)
61+
end if
62+
end if
63+
end insertNode
64+
```
65+
66+
### Searching
67+
68+
```text
69+
contains(root, value)
70+
Pre: root is the root node of the tree, value is what we would like to locate
71+
Post: value is either located or not
72+
if root = ø
73+
return false
74+
end if
75+
if root.value = value
76+
return true
77+
else if value < root.value
78+
return contains(root.left, value)
79+
else
80+
return contains(root.right, value)
81+
end if
82+
end contains
83+
```
84+
85+
86+
### Deletion
87+
88+
```text
89+
remove(value)
90+
Pre: value is the value of the node to remove, root is the node of the BST
91+
count is the number of items in the BST
92+
Post: node with value is removed if found in which case yields true, otherwise false
93+
nodeToRemove ← findNode(value)
94+
if nodeToRemove = ø
95+
return false
96+
end if
97+
parent ← findParent(value)
98+
if count = 1
99+
root ← ø
100+
else if nodeToRemove.left = ø and nodeToRemove.right = ø
101+
if nodeToRemove.value < parent.value
102+
parent.left ← nodeToRemove.right
103+
else
104+
parent.right ← nodeToRemove.right
105+
end if
106+
else if nodeToRemove.left = ø and nodeToRemove.right = ø
107+
if nodeToRemove.value < parent.value
108+
parent.left ← nodeToRemove.left
109+
else
110+
parent.right ← nodeToRemove.left
111+
end if
112+
else
113+
largestValue ← nodeToRemove.left
114+
while largestValue.right = ø
115+
largestValue ← largestValue.right
116+
end while
117+
findParent(largestValue.value).right ← ø
118+
nodeToRemove.value ← largestValue.value
119+
end if
120+
count ← count - 1
121+
return true
122+
end remove
123+
```
124+
125+
### Find Parent of Node
126+
127+
```text
128+
findParent(value, root)
129+
Pre: value is the value of the node we want to find the parent of
130+
root is the root node of the BST and is != ø
131+
Post: a reference to the prent node of value if found; otherwise ø
132+
if value = root.value
133+
return ø
134+
end if
135+
if value < root.value
136+
if root.left = ø
137+
return ø
138+
else if root.left.value = value
139+
return root
140+
else
141+
return findParent(value, root.left)
142+
end if
143+
else
144+
if root.right = ø
145+
return ø
146+
else if root.right.value = value
147+
return root
148+
else
149+
return findParent(value, root.right)
150+
end if
151+
end if
152+
end findParent
153+
```
154+
155+
### Find Node
156+
157+
```text
158+
findNode(root, value)
159+
Pre: value is the value of the node we want to find the parent of
160+
root is the root node of the BST
161+
Post: a reference to the node of value if found; otherwise ø
162+
if root = ø
163+
return ø
164+
end if
165+
if root.value = value
166+
return root
167+
else if value < root.value
168+
return findNode(root.left, value)
169+
else
170+
return findNode(root.right, value)
171+
end if
172+
end findNode
173+
```
174+
175+
### Find Minimum
176+
177+
```text
178+
findMin(root)
179+
Pre: root is the root node of the BST
180+
root = ø
181+
Post: the smallest value in the BST is located
182+
if root.left = ø
183+
return root.value
184+
end if
185+
findMin(root.left)
186+
end findMin
187+
```
188+
189+
### Find Maximum
190+
191+
```text
192+
findMax(root)
193+
Pre: root is the root node of the BST
194+
root = ø
195+
Post: the largest value in the BST is located
196+
if root.right = ø
197+
return root.value
198+
end if
199+
findMax(root.right)
200+
end findMax
201+
```
202+
203+
### Traversal
204+
205+
#### InOrder Traversal
206+
207+
```text
208+
inorder(root)
209+
Pre: root is the root node of the BST
210+
Post: the nodes in the BST have been visited in inorder
211+
if root = ø
212+
inorder(root.left)
213+
yield root.value
214+
inorder(root.right)
215+
end if
216+
end inorder
217+
```
218+
219+
#### PreOrder Traversal
220+
221+
```text
222+
preorder(root)
223+
Pre: root is the root node of the BST
224+
Post: the nodes in the BST have been visited in preorder
225+
if root = ø
226+
yield root.value
227+
preorder(root.left)
228+
preorder(root.right)
229+
end if
230+
end preorder
231+
```
232+
233+
#### PostOrder Traversal
234+
235+
```text
236+
postorder(root)
237+
Pre: root is the root node of the BST
238+
Post: the nodes in the BST have been visited in postorder
239+
if root = ø
240+
postorder(root.left)
241+
postorder(root.right)
242+
yield root.value
243+
end if
244+
end postorder
245+
```
246+
247+
## Complexities
248+
249+
### Time Complexity
250+
251+
| Access | Search | Insertion | Deletion |
252+
| :-------: | :-------: | :-------: | :-------: |
253+
| O(log(n)) | O(log(n)) | O(log(n)) | O(log(n)) |
254+
255+
### Space Complexity
256+
257+
O(n)
258+
259+
## References
260+
261+
- [trekhleb/javascript-algorithms](https://github.com/trekhleb/javascript-algorithms/tree/master/src/data-structures/tree/binary-search-tree)
262+
- [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_tree)
263+
- [Inserting to BST on YouTube](https://www.youtube.com/watch?v=wcIRPqTR3Kc&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=9&t=0s)
264+
- [BST Interactive Visualisations](https://www.cs.usfca.edu/~galles/visualization/BST.html)
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// import visualization libraries {
2+
const { Tracer, Array1DTracer, GraphTracer, LogTracer, Layout, VerticalLayout } = require('algorithm-visualizer');
3+
// }
4+
5+
const T = {};
6+
7+
const elements = [5, 8, 10, 3, 1, 6, 9, 7, 2, 0, 4]; // item to be inserted
8+
9+
// define tracer variables {
10+
const graphTracer = new GraphTracer(' BST - Elements marked red indicates the current status of tree ');
11+
const elemTracer = new Array1DTracer(' Elements ');
12+
const logger = new LogTracer(' Log ');
13+
Layout.setRoot(new VerticalLayout([graphTracer, elemTracer, logger]));
14+
elemTracer.set(elements);
15+
graphTracer.log(logger);
16+
Tracer.delay();
17+
// }
18+
19+
function bstInsert(root, element, parent) { // root = current node , parent = previous node
20+
// visualize {
21+
graphTracer.visit(root, parent);
22+
Tracer.delay();
23+
// }
24+
const treeNode = T[root];
25+
let propName = '';
26+
if (element < root) {
27+
propName = 'left';
28+
} else if (element > root) {
29+
propName = 'right';
30+
}
31+
if (propName !== '') {
32+
if (!(propName in treeNode)) { // insert as left child of root
33+
treeNode[propName] = element;
34+
T[element] = {};
35+
// visualize {
36+
graphTracer.addNode(element);
37+
graphTracer.addEdge(root, element);
38+
graphTracer.select(element, root);
39+
Tracer.delay();
40+
graphTracer.deselect(element, root);
41+
logger.println(`${element} Inserted`);
42+
// }
43+
} else {
44+
bstInsert(treeNode[propName], element, root);
45+
}
46+
}
47+
// visualize {
48+
graphTracer.leave(root, parent);
49+
Tracer.delay();
50+
// }
51+
}
52+
53+
const Root = elements[0]; // take first element as root
54+
T[Root] = {};
55+
// visualize {
56+
graphTracer.addNode(Root);
57+
graphTracer.layoutTree(Root, true);
58+
logger.println(`${Root} Inserted as root of tree `);
59+
// }
60+
61+
for (let i = 1; i < elements.length; i++) {
62+
// visualize {
63+
elemTracer.select(i);
64+
Tracer.delay();
65+
// }
66+
bstInsert(Root, elements[i]); // insert ith element
67+
// visualize {
68+
elemTracer.deselect(i);
69+
Tracer.delay();
70+
// }
71+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy