Thursday, April 30, 2009

sol tut6 ecp1026

#include
#include
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;
void inorder (struct BinTreeNode *node);
void SetTree();
int main(void){
SetTree();
/* traverse and print tree */
printf("\nPreorder traversal:\t"); preorder(root);
printf("\nInorder traversal:\t"); inorder(root);
printf("\nPostorder traversal:\t"); postorder(root);
return(0);
}

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);
}
}
void SetTree(){
/*1*/
root=initBinTreeNode('A');
root->left=initBinTreeNode('B');
root->right=initBinTreeNode('C');
/*2*/
parent1=root->left;
parent1->left=initBinTreeNode('D');
parent1->right=initBinTreeNode('E');
/*3*/
parent2=parent1->right;
parent2->left=initBinTreeNode('H');
parent2->right=initBinTreeNode('I');
/*4*/
parent1=root->right;
parent1->left=initBinTreeNode('E');
parent1->right=initBinTreeNode('G');
/*5*/
parent2=parent1->left;
parent2->left=initBinTreeNode('J');
parent2->right=initBinTreeNode('K');
/*6*/
parent3=parent2->right;
parent3->left=initBinTreeNode('L');
parent3->right=initBinTreeNode('M');
}

No comments: