Contoh Abstract Data Type yang akan dibahas sekarang adalah binary search tree, yaitu tree dengan ketentuan anak kiri <>
# include
# include
typedef struct tree {
int nilai;
struct tree * left;
struct tree * right;
} BTREE;
///////////////FUNGSI MENCETAK PREORDER/////////////
void preorder (BTREE **root)
{
if (*root == NULL);
else
{
printf ("%d \t",(*root)->nilai);
preorder (&(*root)->left);
preorder (& (*root)->right);
}
}
/////////////////fungsi mencetak INORDER//////////////
void inorder (BTREE **root)
{
if (*root == NULL);
else
{
inorder (&(*root)->left);
printf ("%d \t",(*root)->nilai);
inorder (& (*root)->right);
}
}
////////////MENCETAK POSTORDER////////////////
void postorder (BTREE **root)
{
if (*root == NULL);
else
{
postorder (&(*root)->left);
postorder (& (*root)->right);
printf ("%d \t",(*root)->nilai);
}
}
/////////////fungsi memasukan data/////////////
void insert (BTREE **root, int value)
{
BTREE *temp;
temp=(BTREE*) malloc (sizeof (BTREE));
temp -> right = NULL;
temp -> left = NULL;
if (*root==NULL)
{
*root = temp;
(*root)->nilai = value;
}
else
{
if (value <(*root)->nilai)
insert (& (*root)->left, value);
else
insert (& (*root)->right, value);
}
}
int main ()
{
BTREE* root = NULL;
insert (& root, 12);
insert (& root, 4);
insert (& root, 8);
insert (& root, 5);
preorder (& root);
inorder (& root);
postorder (& root);
getch ();
return 0;
}
# include
typedef struct tree {
int nilai;
struct tree * left;
struct tree * right;
} BTREE;
///////////////FUNGSI MENCETAK PREORDER/////////////
void preorder (BTREE **root)
{
if (*root == NULL);
else
{
printf ("%d \t",(*root)->nilai);
preorder (&(*root)->left);
preorder (& (*root)->right);
}
}
/////////////////fungsi mencetak INORDER//////////////
void inorder (BTREE **root)
{
if (*root == NULL);
else
{
inorder (&(*root)->left);
printf ("%d \t",(*root)->nilai);
inorder (& (*root)->right);
}
}
////////////MENCETAK POSTORDER////////////////
void postorder (BTREE **root)
{
if (*root == NULL);
else
{
postorder (&(*root)->left);
postorder (& (*root)->right);
printf ("%d \t",(*root)->nilai);
}
}
/////////////fungsi memasukan data/////////////
void insert (BTREE **root, int value)
{
BTREE *temp;
temp=(BTREE*) malloc (sizeof (BTREE));
temp -> right = NULL;
temp -> left = NULL;
if (*root==NULL)
{
*root = temp;
(*root)->nilai = value;
}
else
{
if (value <(*root)->nilai)
insert (& (*root)->left, value);
else
insert (& (*root)->right, value);
}
}
int main ()
{
BTREE* root = NULL;
insert (& root, 12);
insert (& root, 4);
insert (& root, 8);
insert (& root, 5);
preorder (& root);
inorder (& root);
postorder (& root);
getch ();
return 0;
}
No comments:
Post a Comment