212.Print nodes at k distance from a given node like
Microsoft Interview Questions and Answers
(Continued from previous question...)
212.Print nodes at k distance from a given node like
Question:
Print nodes at k distance from a given node like :
both upper side and lower side
maybe an answer:
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
int printKDistant(node *root , node *gc, int k, int fc)
{
if(root == NULL)
return fc;
if( root->data == gc->data )
{
// printf( "%d ", root->data );
return 1;
}
fc = printKDistant( root->left, gc, k , fc) ;
if(fc)
{
if(fc == k)
{printf("kth = %d\n", root->data);return 0;}
else
return fc+1;
}
else
fc = printKDistant( root->right, gc, k , fc) ;
if(fc)
{
if(fc == k)
{printf("kth = %d\n", root->data);
return 0;
}
else
return fc+1;
}
else
return fc;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
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);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 8
*/
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);
printKDistant(root, root->right, 1, 0);
getchar();
return 0;
}
(Continued on next question...)
Other Interview Questions
|