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 the above Binary Tree, 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:

The basic idea is that if a node is at distance k from the root, then it will be at distance (k-1) from the left child (or Right child).

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

0 Comments

Leave a comment