Print all nodes at distance k from a given node


getting wrong answer in two testcases.
pls tell the correct code.

You did’nt consider the cases when there will be no such nodes at k distances as in those cases you have to print 0 and also u have to print your answer in sorted order

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.

pls tell in the form of a code

@yutikakhanna You can have a look at this.
tree (or subtree) rooted with given root. See */
void printkdistanceNodeDown(node *root, int k)
{
// Base Case
if (root == NULL || k < 0) return;

// If we reach a k distant node, print it 
if (k==0) 
{ 
    cout << root->data << endl; 
    return; 
} 

// Recur for left and right subtrees 
printkdistanceNodeDown(root->left, k-1); 
printkdistanceNodeDown(root->right, k-1); 

}

// Prints all nodes at distance k from a given target node.
// The k distant nodes may be upward or downward. This function
// Returns distance of root from target node, it returns -1 if target
// node is not present in tree rooted with root.
int printkdistanceNode(node* root, node* target , int k)
{
// Base Case 1: If tree is empty, return -1
if (root == NULL) return -1;

// If target is same as root.  Use the downward function 
// to print all nodes at distance k in subtree rooted with 
// target or root 
if (root == target) 
{ 
    printkdistanceNodeDown(root, k); 
    return 0; 
} 

// Recur for left subtree 
int dl = printkdistanceNode(root->left, target, k); 

// Check if target node was found in left subtree 
if (dl != -1) 
{ 
     // If root is at distance k from target, print root 
     // Note that dl is Distance of root's left child from target 
     if (dl + 1 == k) 
        cout << root->data << endl; 

     // Else go to right subtree and print all k-dl-2 distant nodes 
     // Note that the right child is 2 edges away from left child 
     else
        printkdistanceNodeDown(root->right, k-dl-2); 

     // Add 1 to the distance and return value for parent calls 
     return 1 + dl; 
} 

// MIRROR OF ABOVE CODE FOR RIGHT SUBTREE 
// Note that we reach here only when node was not found in left subtree 
int dr = printkdistanceNode(root->right, target, k); 
if (dr != -1) 
{ 
     if (dr + 1 == k) 
        cout << root->data << endl; 
     else
        printkdistanceNodeDown(root->left, k-dr-2); 
     return 1 + dr; 
} 

// If target was neither present in left nor in right subtree 
return -1; 

}