Professional Documents
Culture Documents
Lect 18 - 2024
Lect 18 - 2024
aft
Foundations of
Data Structures and Algorithms
Lect 18
Sameera Muhamed Salam
Dept of CSIS, BITS Pilani, Hyderabad Campus
Dr
Practice question
Your friend is found trespassing in King Ganon’s favorite garden and are sent away to
be executed. Executions in Ganon’s prisons are very odd. If there are n prisoners to be
executed, the prisoners are seated in a row, and then —
▶ The first prisoner is executed, then the third prisoner is executed, then the fifth,
and so on.
▶ Once the nth (if n is odd) or (n − 1)th (if n is even) prisoner is executed, the
process repeats, but this time it starts from the end and every alternate prisoner is
executed.
▶ This process repeats till only one prisoner is left and she or he is set free.
You bribe the prison guard so that your friend will sit in a place chosen by you. Given
the number of prisoners (including your friend), write a program to find which position
to sit so that your friend can survive the execution.
Expected Time complexity of your solution - O(log n).
▶ SEARCH
▶ TRAVERSAL
▶ MINIMUM
▶ MAXIMUM
▶ PREDECESSOR
▶ SUCCESSOR: Find the node with the
smallest key greater than key[x].
▶ INSERT
▶ DELETE.
Figure: Inorder: 1 3 4 6 7 8 10 13 14
▶ If one of the children of node w is an external node, say node z, we simply remove
w and z from T , and replace w with the sibling of z
▶ If both children of node w are internal nodes, we cannot simply remove the node
w from T , since this would create a “hole” in T . Instead, we proceed as follows
1. We find the first internal node y that follows w in an inorder traversal of T . Node y
is the left-most internal node in the right subtree of w, and is found by going first to
the right child of w and then down T from there, following left children. Also, the
left child x of y is the external node that immediately follows node w in the inorder
traversal of T .
2. We save the element stored at w in a temporary variable t, and move the item of y
into w. This action has the effect of removing the former item stored at w.
3. We remove x and y from T by replacing y with x’s sibling, and removing both x and
y from T
4. We return the element previously stored at w, which we had saved in the temporary
variable t.
Every Operations run in O(h) time. what is the maximum height of a BST?