Print All nodes at distance k

Out of 4 only two test cases worked.Test 1 and 2 failed. What is wrong in the code.

Please help me in this question

Anish, pls make following changes in your code :
You need to use vector to store the values… For eg, You can take a global vector, as
vectorv;

Then, you can refer to the code as :

void kthnodefromtarget(node* root, int k)
{
if (root == NULL or k < 0)
{
return;
}

if (k == 0) 
{
    v.push_back(root->data);
	return;
}

kthnodefromtarget(root->left, k - 1);
kthnodefromtarget(root->right, k - 1);
}

int nodeatkthdistancefromtarget(node* root, int target, int k)
{
if (root == NULL)
{
return -1; //target doesn’t exist
}

if (root->data == target) 
{
	kthnodefromtarget(root, k);
	return 0;
}


int L = nodeatkthdistancefromtarget(root->left, target, k);

if (L != -1) 
{ // it means target exists int the left
	if (L + 1 == k) 
    {
        v.push_back(root->data);
	}
	else 
    {
		kthnodefromtarget(root->right, k - L - 2);
	}
	return L + 1; //distance of current node from target node
}

int R = nodeatkthdistancefromtarget(root -> right, target, k);

if (R != -1) 
{
	if (R + 1 == k) 
    {
		
        v.push_back(root->data);
	}
	else 
    {
		kthnodefromtarget(root->left, k - R - 2);
	}
	return R + 1; //distance of current node from target node
}
return -1; //if dleft and dright both are -1
}



and also in the main function, make changes as :

while(T>0)
{
int target,k;
cin>>target>>k;
nodeatkthdistancefromtarget(root,target,k);
if(v.size()==0)
{
cout<<“0”;
}
else
{
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
}
v.erase(v.begin(),v.end());

	cout<<endl;
	T--;
}
1 Like

Thank you so much for helping. :slightly_smiling_face: