Quiz2 Solution
Quiz2 Solution
Question 1 Consider the data structure to store arithmetic expressions using ArithmeticNode
class. Complete the method printPostFix. [3 marks]
void printPostfix() {
if( isOperator ){
left.printPostfix() ;
right.printPostfix() ;
System.out.print(op) ;
}
else{ System.out.print(val) ;}
}
}
Alternative argument: This algorithm performs a postorder traversal of tree. This traversal
takes time which is again order of number of nodes in the tree.
Example:
* 3
4 8
Postfix expression: 4 8 * 3 +
Question 2 Consider an augmented BST where each node x has four attributes: data, left, right,
size; where the size of a node denotes the number of nodes in its subtree (see example below).
data=33
size=6
data=15 data=47
size=3 size=2
Complete the algorithm below to find the k th smallest element in a BST. [2 marks]
x ← head ;
if (k ⪈ x.size) then Raise error;
while (1) do
if (x.left ̸= Null and k ≤ x.left.size) then
x = x.left ;
else if (x.right ̸= Null and k ⪈ x.size − x.right.size ) then
x = x.right ;
k = k − x.size + x.right.size ;
else
Return x.data ;
How will the algorithm and running time change if you do not store ‘size’? [1 marks]
If we do not store size, then we will need to perform an inorder traversal and return the data of
k th node in the traversal. This will take O(n) time in the worst case as compared to O(log n)
running time of above algorithm.
Question 3 In the given AVL tree, perform the following operations and draw the tree after
each opearation. Clearly show the rotations used. The operations are to be performed in order,
i.e., the resultant tree after one operation should be used for the next operation. [3 marks]
20
10 57
12 29 100
90
a. insert 95
b. insert 92
c. delete 10