You are on page 1of 2

All codes must be commented and justified

You get points if your solution is correct


In order to have all the points, you must respect the complexity specifications

1. Implement a data structure supporting the following operation:


- bool empty(): returns 1 if there is no element stored in the structure
- void add(int v): adds a new element equal to v in the structure
- int next(): returns and removes from the structure the middle element (i.e., half of
the elements got inserted after the element returned)
All the operations should run in O(1) time /5
//we keep the n/2 most recent elements in a queue, and all others in a stack
typedef struct{
queue<int> fst;
stack<int> snd;
} data_structure;

bool empty(data_structure& a){ return a.snd.empty(); }

void add(data_structure& a, int v){


a.fst.push(v);
if( a.fst.size() > ( a.fst.size()+a.snd.size() )/2 ){
a.snd.push( a.fst.front() );
a.fst.pop();
}
}

int next(data_structure& a){


int v = a.snd.top();
a.snd.pop();
if( a.fst.size() > ( a.fst.size()+a.snd.size() )/2 ){
a.snd.push( a.fst.front() );
a.fst.pop();
}
return v;
}

2. You are given the pre-order of a binary tree (missing children are indicated by the symbol null).
Example: 4 1 null 3 null null 7 6 null null null
Decide whether this is a binary search tree.
The running time should be in O(n) /5
//One solution would be to construct the binary tree and to check whether it is a
binary search tree
//We here propose a slightly different solution where we needn’t construct the tree

bool bst(1); //final answer


fstream f (``date.in’’,fstream::in); //input file

int value;
bool right;
stack<int> dfs; //in order to simulate the tree

while(bst && !f.eof()){

if(f >> value){ //new value


if(!dfs.empty() && ( ( !right && dfs.top() < value ) || ( right && dfs.top()
>= value ) )) { bst = 0; }
else { dfs.push(value); right = 0; }
}else { //null
if(right) { dfs.pop(); }
right = 1;
f.ignore();
}

f.close();
return bst;

You might also like