#include <iostream>
#include <vector>
#include<math.h>
using namespace std;
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
};
///寻找数中节点与给定值 差值最小的点
int findClosest(TreeNode* root, int value)
{ // write your code here...
// suppose root is not NULL
int temp;
int mintt = value;
int res;
while (root != NULL){
if (value == root->value){
res = root->value;
return res;
}
else if ((value<root->value)&&(root->left!=NULL)){
root = root->left;
temp = abs(root->value - value);
if (mintt >= temp){
mintt = temp;
res = root->value;
}
}
else if(root->right!=NULL){
root = root->right;
temp = abs(root->value - value);
if (mintt >= temp){
mintt = temp;
res = root->value;
}
}
else
return res;
}
return res;
}
bool BSTInsert(TreeNode*& p, int element)
{
if (NULL == p) // 空树
{
p = new TreeNode;
p->value = element;
p->left = p->right = NULL;
return true;
}
if (element == p->value) // BST中不能有相等的值
return false;
if (element < p->value) // 递归
return BSTInsert(p->left, element);
return BSTInsert(p->right, element); // 递归
}
bool createBST(TreeNode*& T, vector<int> values, int n)
{
T = NULL;
int i;
for (i = 0; i < n; i++) {
if (!BSTInsert(T, values[i])){
return false;
}
}
return true;
}
int main()
{ // test and not consider free the used memory
int n;
cin >> n;
vector<int> values(n, 0);
for (int i = 0; i < n; i++){
cin >> values[i];
}
TreeNode* T;
// 并非所有的a[]都能构造出BST,所以,最好对createBST的返回值进行判断
if (createBST(T, values, n)) {
int m;
cin >> m;
for (int i = 0; i < m; i++){
int tmp;
cin >> tmp;
printf("%d\n", findClosest(T, tmp));
//cout << findClosest(T, tmp) << endl;
}
}
return 0;
}/*10
32 47 91 20 59 0 1 88 74 62
10
0 1 80 81 82 58 59 60 61 20*/