#include<cstdio>
using namespace std;
struct node
{
int data;
node *leftchild;
node *rightchild;
};
node *root=NULL;
void insert_data(int data)
{
node *current,*new_node,*parent;
new_node = new node();
new_node->data=data;
new_node->leftchild=NULL;
new_node->rightchild=NULL;
if(root==NULL)
{
root = new_node;
}
else
{
current = root;
parent = NULL;
while(1)
{
parent=current;
if(current->data<data)
{
current=current->rightchild;
if(current==NULL)
{
parent->rightchild=new_node;
return;
}
}
else
{
current=current->leftchild;
if(current==NULL)
{
parent->leftchild=new_node;
return;
}
}
}
}
}
void search_data(int data)
{
node *current;
current=root;
while(current->data!=data)
{
if(current->data<data)
{
current=current->rightchild;
}
else
{
current = current->leftchild;
}
if(current==NULL)
{
printf("Data Not Found\n");
return;
}
}
printf("%d Yea data is Found\n",current->data);
return;
}
int main()
{
int n,data;
printf("how many node\n");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&data);
insert_data(data);
}
printf("Searching data\n");
while(1)
{
scanf("%d",&data);
search_data(data);
}
printf("Searching completed\n");
}
Reference :https://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm
No comments:
Post a Comment