Check if a Binary Tree is Binary Search Tree
August 23, 2012
Find number occurring odd number of times in an array
August 24, 2012

Print all nodes at distance k from root of a Binary Tree

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 ) ;
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *