/*Binary Search Tree along with a search module to find at which level a particular value resides.*/
#include<stdio.h>
#include<conio.h>
struct Tree
{
int data,level;
struct Tree *left;
struct Tree *right;
};
typedef struct Tree node;
node*create_node(int value)
{
node*p=(node*)malloc(sizeof(node));
p->data=value;
p->left=p->right=NULL;
return p;
}
void create_tree(int value,node*root)
{
if(value < root->data)
{
if(root->left==NULL)
root->left=create_node(value);
else
create_tree(value,root->left);
}
else
{
if(root->right==NULL)
root->right=create_node(value);
else
create_tree(value,root->right);
}
}
void inorder(node*root)
{
if(root!=NULL)
{
inorder(root->left);
printf("Data=%d\t",root->data);
printf("Level=%d\n",root->level);
inorder(root->right);
}
}
void level_stamper(node*root,int levl)
{
if(root!=NULL)
{
level_stamper(root->left,levl+1);
root->level=levl;
level_stamper(root->right,levl+1);
}
}
node *find_node(node *root,int value)
{
static node *ret_addr=NULL;
if(root!=NULL)
{
find_node(root->left,value);
if(root->data==value)
ret_addr=root;
find_node(root->right,value);
}
return ret_addr;
}
int main()
{
node*srch;
node*root=create_node(10);
create_tree(14,root);
create_tree(12,root);
create_tree(15,root);
create_tree(8,root);
create_tree(9,root);
level_stamper(root,0);
inorder(root);
if((srch=find_node(root,9)))
printf("Found at level %d\n",srch->level);
else
printf("Not Found\n");
getche();
return 1;
}
0 comments:
Post a Comment