#include <stdio.h>
#include <stdlib.h>

struct bnt_t{
    int V;
    int U;
    struct bnt_t* left;
    struct bnt_t* right;
};

struct bnt_t* init(int V, int U);
void print_tree(struct bnt_t* root);
int how_many(int V, struct bnt_t* root, int res);
struct bnt_t* add_to_tree(int V, int U, struct bnt_t* root);
struct bnt_t* where(int V, struct bnt_t* root);

int main(){
    struct bnt_t* root = init(2, 0);
    int N = 0, U = 0, V = 0, Q = 0, M = 0;
    int* ans;

    do{
        printf("Enter N: ");
        scanf("%d", &N);
    }while(N < 1 || N > 100000);

    for(int i = 0; i < N - 1; i++){
        printf("Enter U - under, V - number: ");
        scanf("%d %d", &U, &V);
        getchar();
        add_to_tree(V, U, root);
    }

    do{
        printf("Enter Q: ");
        scanf("%d", &Q);
    }while(Q < 1 || Q > N);

    ans = (int*)malloc(sizeof(int) * Q);

    for(int i = 0; i < Q; i++){
        printf("Enter Number: ");
        scanf("%d", &M);
        ans[i] = how_many(M, where(M, root), 0);
    }

    for(int i = 0; i < Q; i++)
        printf("%d\n", ans[i]);

    return 0;
}

struct bnt_t* where(int V, struct bnt_t* root){
    struct bnt_t* temp = root;

    if(temp->V == V)
        return temp;
    else if(temp->left != NULL) where(V, temp->left);
    else if(temp->right != NULL) where(V, temp->right);
    else
        return temp;
}

int how_many(int V, struct bnt_t* root, int res){
    struct bnt_t* temp = root;

    printf("Root->v %d", root->V);

    if(temp->left != NULL) how_many(V, temp->left, res++);
    if(temp->right != NULL) how_many(V, temp->right, res++);

    return res;
}


struct bnt_t* add_to_tree(int V, int U, struct bnt_t* root){
    struct bnt_t* temp = root;
    if(U == temp->V){
        if(V > temp->V){
            while(temp->right != NULL)
                temp = temp->right;
            temp->right = init(V, U);
        }
        else{
            while(temp->left != NULL)
                temp = temp->left;
            temp->left = init(V, U);
        }
    }
    else{
        if(V > temp->V){
            if(temp->right != NULL)
                add_to_tree(V, U, temp->right);
            else{
                temp->right = init(V, U);
                return root;
            }
        }
        else{
            if(temp->left != NULL)
                add_to_tree(V, U , temp->left);
            else{
                temp->left = init(V, U);
                return root;
            }
        }
    }

    return root;
}

void print_tree(struct bnt_t* root){
    if(root->left != NULL) print_tree(root->left);
    if(root->right != NULL) print_tree(root->right);
    printf("V: %d, U: %d\n", root->V, root->U);
}

struct bnt_t* init(int V, int U){
    struct bnt_t* root = (struct bnt_t*)malloc(sizeof(struct bnt_t));

    root->U = U;
    root->V = V;
    root->left = root->right = NULL;

    return root;
}
