Friday, 4 November 2016

Program 16 - Expression Tree



#include <stdio.h>
#include <stdlib.h>
struct node {
char data;
struct node *left, *right;
};
struct node *build_tree(char postfix[]) {
struct node *stack[100], *nn;
int i, top = -1;
char ch;
for(i = 0; postfix[i] != '\0'; i++) {
ch = postfix[i];
nn = (struct node *)malloc(sizeof(struct node));
nn -> data = ch;
nn -> left = nn -> right = NULL;
if(isdigit(ch) || isalpha(ch)) {
stack[++top] = nn;
} else if(ch == '+' || ch == '-' || ch == '*' || ch == '/') {
nn -> right = stack[top--];
nn -> left = stack[top--];
stack[++top] = nn;
} else {
printf("Invalid Expression\n");
}
}
return stack[top--];
}
void inorder(struct node *root) {
if(root != NULL) {
inorder(root -> left);
printf("%c", root -> data);
inorder(root -> right);
}
}
void preorder(struct node *root) {
if(root != NULL){
printf("%c", root -> data);
preorder(root -> left);
preorder(root -> right);
}
}
void postorder(struct node *root) {
if(root != NULL) {
postorder(root -> left);
postorder(root -> right);
printf("%c", root -> data);
}
}
int main() {
struct node *root;
char postfix[20];
printf("Enter postfix expression: \n");
gets(postfix);
root = build_tree(postfix);
printf("Inorder: ");
inorder(root);
printf("\nPreorder: ");
preorder(root);
//And now *drumroll*
printf("\nPostorder: ");
postorder(root);
}










































































































































No comments:

Post a Comment