[CSE 225] Lecture 21
[CSE 225] Lecture 21
Basic Operations
Find
Find
Input: Key k, Root R
Output: The node in the tree of R with key
k
Idea
Find(6)
Idea
Find(6)
Idea
Find(6)
Idea
Find(6)
Algorithm
Find(k, R)
if R.Key = k: return R
else if R.Key > k :
return Find(k, R.Left)
else if R.Key < k :
return Find(k, R.Right)
Missing Key
Run Find(5).
if R is null:
return "Key not found" # Handle case when tree is empty or key is not found
if R.Key == k:
return R # Key found
else:
return Find(k, R.Right) # Search in the right subtree
Insert
Insert
Input: Key k and root R
Output: Adds node with key k to the tree
Insert Idea
Insert(3)
Insert Idea
Insert(3)
Implementation
Insert(k, R)
P ← Find(k, R)
Add new node with key k as child of
P
Delete
Delete
Input: Node N
Output: Removes node N from the tree
Difficulty
Cannot simply remove.
Delete(13)
Idea
Idea
Idea
Idea
Problem
Which of the following trees is obtained
when the selected node is deleted?
Problem
Which of the following trees is obtained
when the selected node is deleted?
AVL Tree
❑An AVL tree is a type of self-balancing binary search tree named after its
inventors Adelson-Velsky and Landis.
❑This ensures that the worst-case time complexity for common operations
such as searching, insertion, and deletion is O(log n).
Left rotation
Right rotation
• A single rotation applied when a node is inserted in the
right subtree of a right subtree.
• node Ahas a balance factor of 2 after the insertion
of node C.
• By rotating the tree left, node Bbecomes the root
resulting in a balanced tree.
Left-Right Rotation
2 1
Fig 1 2
Fig 4
3
Fig 2
2 1 2
Fig 3
1
1 3
3
Fig 5 Fig 6 4
4
5
2
2
1 4
1 4
3 5
3 5
Fig 8
Fig 7 6
4
4
2 5
2 5
1 3 6
1 3 6
4
Fig 10 7
Fig 9
2 6
1 3 7
5 Fig 11
4 4
2 6 2 6
1 3 7 1 3 7
5 16 5 16
Fig 12
Fig 13
15
4
2 6
1 3 15
5
16
Fig 14 7
4 4
2 6 2 7
15 1 3 15
1 3 5 6
16
7 16
5 14
Fig 15
14 Fig 16
Instructions: