#include <iostream.h>
#include <conio.h>
typedef struct Node{
int data;
Node *kiri;
Node *kanan;
}Node;
void tambah(Node **root,int databaru){
if((*root)== NULL){
Node *baru;
baru = new Node;
baru->data = databaru;
baru->kiri = NULL;
baru->kanan = NULL;
(*root)= baru;
(*root)->kiri = NULL;
(*root)->kanan= NULL;
cout<<"data bertambah!";
}else if(databaru<(*root)->data){
tambah(&(*root)->kiri,databaru);
}else if(databaru>(*root)->data){
tambah(&(*root)->kanan,databaru);
}else if(databaru == (*root)->data){
cout<<"data sudah ada!";
}
}
void preOrder(Node *root){
if(root!=NULL){
cout<<root->data;
preOrder(root->kiri);
preOrder(root->kanan);
}
}
void inOrder (Node *root){
if(root!=NULL){
inOrder(root->kiri);
cout<<root->data;
inOrder(root->kanan);
}
}
void postOrder(Node *root){
if(root!=NULL){
postOrder(root->kiri);
postOrder(root->kanan);
cout<<root->data;
}
}
int count(Node *root)
{
if (root == NULL) return 0;
return count(root->kiri) + count(root->kanan) + 1;
}
Node *FindMin(Node *root)
{
if(root == NULL)
return NULL;
else
if(root->kiri == NULL)
return root;
else
return FindMin(root->kiri);
}
void main(){
int pil;
Node *pohon ;
pohon=NULL;
do{
clrscr();
int data;
cout<<"PROGRAM TREE SEDERHANA \n----------------------\n";
cout<<" Pilih Menu :\n";
cout<<" 1. Tambah Node\n";
cout<<" 2. Lihat Pre-order\n";
cout<<" 3. Lihat In-order\n";
cout<<" 4. Lihat Post-order\n";
cout<<" 5. Hitung Jumlah Node\n";
cout<<" 6. Cari Node Terkecil\n";
cout<<" 7. Exit\n";
cout<<" -->> : ";cin>>pil;
switch(pil){
case 1: cout<<"data baru :";
cin>>data;
tambah(&pohon,data);
break;
case 2 : if(pohon!=NULL)
preOrder(pohon);
else
cout<<"masih kosong!";
break;
case 3 : if(pohon!=NULL)inOrder(pohon);
else cout<<"masih kosong!";
break;
case 4 : if(pohon!=NULL)
postOrder(pohon);
else
cout<<"masih kosong!";
break;
case 5 : if(pohon!=NULL)
cout<<"Jumlah data : "<<count(pohon);
else cout<<"masih kosong!";
break;
case 6 : if(pohon!=NULL){
Node *t = FindMin(pohon);
cout<<"Node terkecil : "<< t->data; }
else cout<<"masih kosong!";
break;
}
getch();
}while(pil!=7);
}
dong?
Sign up here with your email
ConversionConversion EmoticonEmoticon