我正在尝试遍历 C 中的二叉树。我的树包含一个 AST 节点(编译器的抽象语法树节点)。 ASTnode 保留了指定给定节点类型的节点类型(即 INT OP 或 CHAR 和 TYPE 我们不需要关心其他类型),其他成员是左指针和右指针,最后我们存储。
遍历代码如下:
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;
}
}
此外,我们不能将左值或右值分配给 CONSTANT 节点,因为在 AST 中,常量值不包含任何额外值。
更新:
问题出在我的主调用中:
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);
}
如果我们删除 node5(用 !! 标记),代码运行良好,否则会出现段错误。
在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;
}
最佳答案
你的 mallocs 是错误的
struct decl *d = (struct decl*) malloc(sizeof(struct decl*));
struct decl *d2 = (struct decl*) malloc(sizeof(struct decl*));
需要
struct decl *d = (struct decl*) malloc(sizeof(struct decl));
struct decl *d2 = (struct decl*) malloc(sizeof(struct decl));
(或使用 sizeof *d 而不是 sizeof(struct decl))。在 C 中,您不需要转换 malloc 的返回值,顺便说一句。
此外,请确保在访问成员之前将成员设置为 NULL 或其他默认值。 malloc 不会为您将它们设置为 0/NULL。
关于c - C语言遍历二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1963677/