Rabu, 09 April 2014

Code Binary Search Tree

Ini code untuk binasy search tree(BST) dari dosen saya(ko sky), tapi untuk code ini masih ada error nya, so, wait for update :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//Binary Search Tree
struct MLM{
char nama[25];
int usia;
int level;
struct MLM *left, *right, *parent;
}*root;

void push(struct MLM **curr, char nama[], int usia, int level){
if(*curr == NULL){
(*curr) = (struct MLM*)malloc(sizeof(struct MLM));
// Presendence (kurung)
strcpy((*curr)->nama, nama);
(*curr)->usia = usia;
(*curr)->level = level;
(*curr)->left = (*curr)->right = NULL;
}else{
if(usia < (*curr)->usia){
if(*curr != NULL){
(*curr)->left->parent = (*curr);
}
push(&(*curr)->left,nama,usia,level+1);
}else if(usia > (*curr)->usia){
if((*curr) != NULL){
(*curr)->right->parent = (*curr);
}
push(&(*curr)->right,nama,usia,level+1);
}else{
printf("Angka %d sudah ada\n",usia);
}
}
}

void preorder(struct MLM *curr){
if(curr == NULL){
//printf("Maaf, kosong.. coba lagi besok.\n");
//getchar();
}else{
printf("%s %d %d\n",curr->nama, curr->usia, curr->level);
preorder(curr->left);
preorder(curr->right);
}
}

void inorder(struct MLM *curr){
if(curr == NULL){
//printf("Maaf, kosong.. coba lagi besok.\n");
//getchar();
}else{
inorder(curr->left);
printf("%s %d %d\n",curr->nama, curr->usia, curr->level);
inorder(curr->right);
}
}

void postorder(struct MLM *curr){
if(curr == NULL){
//printf("Maaf, kosong.. coba lagi besok.\n");
//getchar();
}else{
postorder(curr->left);
postorder(curr->right);
printf("%s %d %d\n",curr->nama, curr->usia, curr->level);
}
}



void popALL(struct MLM *curr){
if(curr != NULL){
popALL(curr->left);
popALL(curr->right);
free(curr);
}
}

void pop(struct MLM **curr, char nama[]){
if(*curr==NULL){
printf("Not found !\n");
//kosong cuy
}else{
if(strcmpi(nama,(*curr)->nama) < 0){
pop(&(*curr)->left, nama);
}else if(strcmpi(nama, (*curr)->nama) > 0){
pop(&(*curr)->right,nama);
}else if(strcmpi(nama, (*curr)->nama) == 0){
printf("Nemu coy\n");
free(*curr);
}
}

}

int main(){
push(&root,"hehe",20,0);
push(&root,"hue",19,0);

//pop(&root,"hehe");
inorder(root);
return 0;
}

NB : Bahan yang ditulis berdasarkan apa yang pernah saya pelajari dari dosen dan juga slide-slide powerpoint dari Binus University.


Binus University     Skyconnectiva

Tidak ada komentar:

Posting Komentar