I'm trying to solve this problem in a judge online.
The problem provides N integers that must be inserted, in the given order, into an algorithm for inserting a binary search tree. Then Q queries are performed. For each query the code should say who is the parent of the element that is provided in the input.
The entry will be as follows:
N (quantity of values)
N N N 2 ... N N (These are the values that must be entered in the tree) strong> (the amount of queries)
Q Q (the integer representing the position of the given value in the input)
For the following sample entry following the above specification:
5 3 1 4 2 5 2 2 5
The algorithm should form the following tree:
And with this tree must answer who is the parent of the second element given in the entry (the parent of 1) and the 5 element of the entry (the father of 5) separated by a space (there are no spaces after the last value of the output)
Example of expected output for the example entry:
3 4
To solve this problem I used the trivial algorithm of insertion in binary trees (which leads to a worst-case complexity of O (n 2 )). During insertion, you have already saved the parent of each node on a map.
But, the code was judged as timeout exceeded . Is there any faster insertion algorithm than the trivial one (which keeps the order given in the input ... AVL trees will change the parents of each in ...)?
#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]]);
}
Thanks for any help =)