/*Level : Easy question */
#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;
};
/* Helper function to create a new node */
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);
}
/*Utility function to determine path from root to leaf with given distance exists or not*/
int kdistance(struct node *root , int dist)
{
if(!root)
return 0;
if(dist==0 && root->left == NULL && root->right == NULL)
{
printf("leaf reached when k = 0 is %d\n",root->data);
return 1;
}
else
{
(--dist);
return (kdistance(root->left,dist)) || (kdistance(root->right,dist)) ;
}
}
/* Driver program*/
int main()
{
struct node *root1 = newNode(1);
root1->left = newNode(2);
root1->right = newNode(3);
root1->left->left = newNode(4);
root1->left->right = newNode(5);
root1->right->left = newNode(6);
root1->right->right = newNode(7);
int k=2;
if(kdistance(root1,k))
printf("Path exists for k = %d\n",k);
else
printf("Path does not exist for k = %d\n",k);
getchar();
return 0;
}
Thursday, 10 July 2014
Problem Statment: Given a binary tree, find if there exists a root to leaf path of distance k.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment