Heap BST AVL Algorithms
Heap BST AVL Algorithms
BST Insertion
BST-INSERTION(root, key):
if root = NULL:
return NEWNODE(key)
return root
2. BST Deletion
BST-DELETION(root, key):
if root = NULL:
return NULL
temp ← MIN-VALUE(root.right)
root.key ← temp.key
root.right ← BST-DELETION(root.right, temp.key)
return root
MIN-VALUE(node):
while node.left ≠ NULL:
node ← node.left
return node
A[1] ← A[n]
n ← n - 1
MAX-HEAPIFY(A, 1, n)
if largest ≠ i:
swap A[i], A[largest]
MAX-HEAPIFY(A, largest, n)
BUILD-MAX-HEAP(A, n):
for i ← ⌊n / 2⌋ downto 1: /* as there are n/2 leaf nodes so they’re
already a heap */
MAX-HEAPIFY(A, i, n)
7. AVL Rotations
RIGHT-ROTATE(y):
x ← y.left
T2 ← x.right
x.right ← y
y.left ← T2
y.height ← 1 + MAX(HEIGHT(y.left), HEIGHT(y.right))
x.height ← 1 + MAX(HEIGHT(x.left), HEIGHT(x.right))
return x
LEFT-ROTATE(x):
y ← x.right
T2 ← y.left
y.left ← x
x.right ← T2
return y
LEFT-RIGHT-ROTATE(z):
z.left ← LEFT-ROTATE(z.left)
return RIGHT-ROTATE(z)
RIGHT-LEFT-ROTATE(z):
z.right ← RIGHT-ROTATE(z.right)
return LEFT-ROTATE(z)
8. AVL Insertion
AVL-INSERTION(root, key):
if root = NULL:
return NEWNODE(key)
return root
9. AVL Deletion
AVL-DELETION(root, key):
if root = NULL:
return NULL
temp ← MIN-VALUE(root.right)
root.key ← temp.key
root.right ← AVL-DELETION(root.right, temp.key)
return root
10. Heapsort
HEAPSORT(A, n):
BUILD-MAX-HEAP(A, n)
for i ← n downto 2:
swap A[1], A[i]
n ← n - 1
MAX-HEAPIFY(A, 1, n)
10. BFS
BFS(G, start):
create a queue Q
mark start as visited and enqueue it into Q
while Q is not empty:
v = Q.dequeue()
for all neighbors u of v:
if u is not visited:
mark u as visited
Q.enqueue(u)
13. DFS
DFS(G, v):
mark v as visited
for each neighbor u of v:
if u is not visited:
DFS(G, u)
14. Kruskal’s Algorithm
KRUSKAL(G):
A = empty set
for each vertex v in G:
MAKE-SET(v)
return A
key[start] = 0
Q = all vertices in G
dist[source] = 0
Q = all vertices in G
stack.push(v)
18. Huffmann Tree
HUFFMAN(C):
create a priority queue Q with characters and their frequencies