BINARY SEARCH TREE
#include <stdio.h>
#include <malloc.h>
int ketemu = 0;
typedef struct element
{
int data;
struct element * left;
struct element * right;
}element;
element * createdtree(int data)
{
element * buat;
buat = (element*)malloc(sizeof(element));
buat-> data = data;
buat->left = NULL;
buat-> right = NULL;
}
void insertdata(int data, element **tree)
{
if((*tree)==NULL)
{
(*tree)= createdtree(data);
}else if(data >= (*tree)->data)
{
insertdata(data,&(*tree)->right);
}else
{
insertdata(data,&(*tree)->left);
}
}
void preorder(element * tree)
{
if(tree == NULL) return;
printf("%d",tree->data);
preorder(tree->left);
preorder(tree->right);
}
void searchdata(element ** tree,int cari)
{
if((*tree) !=NULL)
{
if((*tree)->data == cari)
{
ketemu = 1;
}else if((*tree)->data > cari)
{
searchdata(&(*tree)->left,cari);
}else
{
searchdata(&(*tree)->right,cari);
}
}
}
int main()
{
element * tree= NULL;
insertdata(10,&tree);
insertdata(11,&tree);
insertdata(9,&tree);
insertdata(100,&tree);
preorder(tree);
searchdata(&tree,70);
if(ketemu == 1)
{
printf("ada");
}else
{
printf("g ada");
}
}
Komentar
Posting Komentar