Last active
August 29, 2015 13:58
-
-
Save halit/9940998 to your computer and use it in GitHub Desktop.
simple abstract syntax tree and eval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef union{ | |
int i; | |
char c; | |
}_value; | |
typedef struct _node{ | |
struct _node* left; | |
struct _node* right; | |
_value value; | |
}node; | |
int eval(node* current){ | |
if(current->value.c == '+') return eval(current->left) + eval(current->right); | |
if(current->value.c == '-') return eval(current->left) - eval(current->right); | |
if(current->value.c == '/') return eval(current->left) / eval(current->right); | |
if(current->value.c == '*') return eval(current->left) * eval(current->right); | |
else return current->value.i; | |
} | |
void visit(_value v){ | |
if(v.i > 9) printf("%c", v.c); | |
else printf("%d", v.i); | |
} | |
void preorder(node* current){ | |
if(current != NULL){ | |
visit(current->value); | |
preorder(current->left); | |
preorder(current->right); | |
} | |
} | |
void inorder(node* current){ | |
if(current != NULL){ | |
inorder(current->left); | |
visit(current->value); | |
inorder(current->right); | |
} | |
} | |
void postorder(node* current){ | |
if(current != NULL){ | |
postorder(current->left); | |
postorder(current->right); | |
visit(current->value); | |
} | |
} | |
int main(int argc, const char *argv[]){ | |
size_t node_numbers = 7; | |
size_t i; | |
node** nodes = (node**)malloc(sizeof(node)*node_numbers); | |
for(i=0;i<node_numbers;i++) nodes[i] = (node*)malloc(sizeof(node)); | |
nodes[0]->value.c = '+'; // root node | |
nodes[1]->value.c = '-'; | |
nodes[2]->value.i = 4; | |
nodes[3]->value.i = 1; | |
nodes[4]->value.c = '*'; | |
nodes[5]->value.i = 2; | |
nodes[6]->value.i = 3; | |
nodes[0]->left = nodes[1]; | |
nodes[0]->right = nodes[2]; | |
nodes[1]->left = nodes[3]; | |
nodes[1]->right = nodes[4]; | |
nodes[4]->left = nodes[5]; | |
nodes[4]->right = nodes[6]; | |
printf("%d\n", eval(nodes[0])); | |
preorder(nodes[0]); | |
printf("\n"); | |
inorder(nodes[0]); | |
printf("\n"); | |
postorder(nodes[0]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment