Given a Binary Tree and a positive integer ‘k’, write code which will print all the nodes which are at distance ‘k’ from the root.
For example: For Binary Tree on the right side, Following are the nodes which should get printed for the below values of ‘k’
k output --- ------- 0 10 1 5 30 2 4 8 40 3 1
Solution:
void printNodeAtDistance(Node *root , int k)
{
if(root == NULL || k < 0)
return;
if( k == 0 )
{
printf( "%d ", root->data );
}
else
{
printNodeAtDistance( root->left, k-1 ) ;
printNodeAtDistance( root->right, k-1 ) ;
}
}