Tuesday, February 17, 2015

Print nodes at k distance from root

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node* left;
    struct node* right;
};

struct node* newNode(int data)
{
    struct node* node = (struct node*)
                             malloc(sizeof(struct node));
    node->data  = data;
    node->left  = NULL;
    node->right = NULL;

    return(node);
}
printDistance(struct node *root,int x,int k)
{
if(root==NULL)
{
return;
}
if(k==x)
{
printf("%10d  ",root->data);
}
else
{
printDistance(root->left,x+1,k);
printDistance(root->right,x+1,k);
}
}
int main(void)
{
     struct node *root = newNode(1);
  root->left        = newNode(2);
  root->right       = newNode(3);
  root->left->left  = newNode(4);
  root->left->right = newNode(5);
  root->right->left = newNode(8);
  printDistance(root,0,2);
return 0;
}