Monday, March 16, 2009

ecp1026 tut6

short note:

aarrrggGGGHHHHHHHHHHHHH!!!!!!!!!!!!!!!

*********************************************

preorder : A B D E H I C F J K L M G

inorder : D B E H I A J F K L M C G

postorder : D H I E B J L M K F G C A



#include < stdio.h >
#include < stdlib.h >
struct BinTreeNode {
char data;
struct BinTreeNode *left;
struct BinTreeNode *right;
};
struct BinTreeNode *initBinTreeNode(char data);
void visit(char data);
void preorder(struct BinTreeNode *node);
void postorder(struct BinTreeNode *node);
struct BinTreeNode *root, *parent1, *parent2, *parent3;

SetTree();


int main(void){
/* Call function SetTree to grow the tree above */

void SetTree();

struct BinTreeNode *root, *parent1, *parent2;
/* growing the tree */
root = initBinTreeNode('A');
root->left = initBinTreeNode('B');
root->right = initBinTreeNode('C');

parent1 = root->left;
parent1->left = initBinTreeNode('D');
parent1->right = initBinTreeNode('E');

parent1 = root->right;
parent2->left = initBinTreeNode('F');
parent2->right = initBinTreeNode('G');

parent2 = parent1->right;
parent2->left = initBinTreeNode('H');
parent2->right = initBinTreeNode('I');

parent2 = parent1->left;
parent2->left = initBinTreeNode('J');
parent2->right = initBinTreeNode('K');

parent3 = parent2->right;
parent2->left = initBinTreeNode('L');
parent2->right = initBinTreeNode('M');

/* traverse and print tree */

printf("\nPreorder traversal:\t"); preorder(root);
printf("\nInorder traversal:\t"); inorder(root);
printf("\nPostorder traversal:\t"); postorder(root);
return(0);

printf("\nPreorder traversal:\t"); preorder(root);
// Call function inorder to traverse and print tree above
printf("\nPostorder traversal:\t"); postorder(root);
return(0);
}


A
D
B C
E F G
H I J K
L M
void visit(char data){printf("%c ", data);}
struct BinTreeNode *initBinTreeNode(char data){
struct BinTreeNode *temp;
temp = (struct BinTreeNode *)
malloc(sizeof(struct BinTreeNode));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return(temp);
}
void preorder(struct BinTreeNode *node){
if (node){ /* if Node exists */
visit(node->data);
preorder(node->left);
preorder(node->right);
}
}
void postorder(struct BinTreeNode *node){
if (node){
postorder(node->left);
postorder(node->right);
visit(node->data);
}
}

void inorder(struct BinTreeNode *node){
if (node){
inorder(node->left);
visit(node->data);
inorder(node->right);
}
}


4 comments:

-----3riC---- said...

your function prototype for SetTree and inorder missing ^^

-EdwiN- said...

no lah..my function prototype n definition all campur rojak d..haha

reddishTea said...

wah geng wor.. haha XD

Johnny Ong said...

very blur hehe