I am trying to cross a binary tree in C. My tree contains an AST node (abstract syntax node tree for the compiler). ASTnode reserves a nodetype that specifies the given node type (for example, INT OP or CHAR and TYPE, we do not need to relate to other types), the rest of the members are pointers left and right, and finally we save.
Here is the code to move:
void traverse(struct ASTNode *root) { if(root->nodeType == OP){ printf("OP \n"); if(root->left != NULL){ printf("left - "); traverse(root->left); } if(root->right != NULL){ printf("right - "); traverse(root->right); } return; } else{ if(root != NULL && root->nodeType == INT) { printf("INT - "); printf("INT: %d\n",root->value); } if(root != NULL && root->nodeType == CHAR) { printf("CHAR - "); printf("CHAR: %c\n",root->chValue); } return; } }
Also, we cannot assign left or right CONSTANT values ββto nodes, because in AST, constant values ββdo not contain any additional values.
Updated:
The problem is my main call:
int main() { struct ASTNode *node1 = makeCharNode('a'); struct ASTNode *node2 = makeCharNode('b'); struct ASTNode *node10 = makeCharNode('c'); struct ASTNode *node3 = makeINTNode(19); struct decl *d = (struct decl*) malloc(sizeof(struct decl*)); struct decl *d2 = (struct decl*) malloc(sizeof(struct decl*)); struct ASTNode *node4 = makeNode(3,d,node3,node2); struct ASTNode *node5 = makeNode(3,d2,node4,node1); !! traverse(node4); }
If we remove node5 (which is marked with the symbol !!), the code works very well, otherwise it will give a segmentation error.
Functions that work on makenode :
struct ASTNode *makeNode(int opType,struct decl *resultType,struct ASTNode *left,struct ASTNode *right) { struct ASTNode *node= (struct ASTNode *) malloc(sizeof(struct ASTNode *)); node->nodeType = opType; node->resultType = resultType; node->left = left; node->right = right; return node; } struct ASTNode *makeINTNode(int value) { struct ASTNode *intnode= (struct ASTNode *) malloc(sizeof(struct ASTNode *)); intnode->nodeType = INT; intnode->value = value; return intnode; } struct ASTNode *makeCharNode(char chValue) { struct ASTNode *charNode = (struct ASTNode *) malloc(sizeof(struct ASTNode *)); charNode->nodeType = CHAR; charNode->chValue = chValue; return charNode; }