2
I’m trying to solve this problem in an online Judge.
The problem provides N integers that must be inserted, in the given order, into an insertion algorithm of a binary search tree. After Q queries are performed. For each query the code must tell who is the parent of the element that is provided in the input.
The entry will be as follows:
N (amount of values)
N1 N2 ... NN (These are the values to be entered in the tree)
Q (the amount of consultations)
Q1 Q2 ... QQ (the integer representing the position of the given value in the input)
For the following example of input following the above specification:
5 3 1 4 2 5 2 2 5
The algorithm must form the following tree:
And with this tree must answer who is the parent of the second input element (the parent of 1) and the 5 input element (the parent of 5) separated by a space (no spaces after the last output value)
Example of expected output for example input:
3 4
To solve this problem I used the trivial binary tree insertion algorithm (What takes a worst-case complexity of O(n2)). During insertion, already save the parent of each node on a map.
But the code was judged to be time limit exceeded. Is there any insertion algorithm faster than the trivial (which keeps the order given in the input ... AVL trees will change the parents of each in the...)?
#include <cstdio>
#include <cstdlib>
#include <unordered_map>
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
void insertAndBuildFather(node **tree, int data, std::unordered_map<int, int> &father){
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
struct node *root = *tree;
if(root == NULL){
root = tempNode;
father[root->data] = -1; //raiz nao tem pai
*tree = root;
return;
}
struct node *current = root;
struct node *parent = NULL;
while(1){
parent = current;
if(data < parent->data){
current = current->leftChild;
if(current == NULL){
father[tempNode->data] = parent->data;
parent->leftChild = tempNode;
return;
}
}
else{
current = current->rightChild;
if(current == NULL){
father[tempNode->data] = parent->data;
parent->rightChild = tempNode;
return;
}
}
}
}
int main ( void ) {
int n;
scanf("%d", &n);
struct node* tree = NULL;
std::unordered_map<int, int> father; //guarda os pais de cada valor
int in[n + 1];
for (int i = 1; i <= n; ++i) {
scanf("%d", &in[i]);
insertAndBuildFather(&tree, in[i], father);
}
int q, qi;
scanf("%d", &q);
for (int i = 1; i < q; ++i) {
scanf("%d", &qi);
printf("%d ", father[in[qi]]);
}
scanf("%d", &qi);
printf("%d\n", father[in[qi]]);
}
I appreciate any help =)
How strange for us ... This solution is still (N 2) ... in these cases should have more information about the T.T problem ... thanks for the help
– Felipe
Yes, it’s still N², but the test cases are poorly done enough to pass by placing only the extreme cases on the sheets :D
– Gabriel Taets