Print all node from distance k from a given node

#include <iostream>
using namespace std;**strong text**
class node{
public:
    int data;
    node *left;
    node *right;
    node(int d)
    {
        data = d;
        left = NULL;
        right = NULL;
    }
};
int c=0;
node *build(int pre[], int ino[], int s, int e)
{
    if(s>e)
        return NULL;
    static int i=0;
    node *root = new node(pre[i]);
    int index = -1, j;
    for(j=s;j<=e;j++)
    {
        if(pre[i] == ino[j])
            index = j;
    }
    i++;
    root->left = build(pre, ino, s, index-1);
    root->right = build(pre, ino, index+1, e);
    return root;
}
void printkthlevel(node *root, int k)
{
    if(root == NULL)
        return ;
    if(k == 0)
    {
        cout<<root->data<<" ";
        c=1;
    }
    printkthlevel(root->left, k-1);
    printkthlevel(root->right, k-1);
}
int PrintNodeAtDistanceK(node *root, int target, int k)
{
    if(root == NULL)
        return -1;
    if(root->data == target)
    {
        printkthlevel(root, k);
        return 0;
    }
    int dl = PrintNodeAtDistanceK(root->left, target, k);
    if(dl != -1)
    {
        if(dl+1 == k)
        {
            cout<<root->data<<" ";
            c=1;
        }
        else
            printkthlevel(root->right, k-dl-2);
        return 1+dl;
    }
    int dr = PrintNodeAtDistanceK(root->right, target, k);
    if(dr != -1)
    {
        if(dr+1 == k)
        {
            cout<<root->data<<" ";
            c=1;
        }
        else
            printkthlevel(root->left, k-dr-2);
        return 1+dr;
    }
    return -1;
}
int main()
{
    int n, i;
    cin>>n;
    int pre[n], ino[n];
    for(i=0;i<n;i++)
        cin>>pre[i];
    for(i=0;i<n;i++)
        cin>>ino[i];
    int test;
    cin>>test;
    node *root = build(pre, ino, 0, n-1);
    while(test--)
    {
        int d, k;
        cin>>d>>k;
        PrintNodeAtDistanceK(root, d, k);
        if(c == 0)
            cout<<0;
        c=0;
        cout<<endl;
    }
}

yr code seems fine… u may not be able to pass all test cases as u have to print nodes in the increasing value… so just store them in a vector/array then sort it and print… if u still face any issues do let e know…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.