我想遍历C中的二叉树。我的树包含一个AST节点(编译器的抽象语法树节点)。 ASTnode保留指定给定节点类型的节点类型(即INT OP或CHAR和TYPE,我们不需要关心其他类型),其他成员是左指针和右指针,最后我们存储。遍历C中的二叉树C
这里是穿越代码:
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;
}
}
同时,我们也不能分配左边或右边的值恒定的节点,因为在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);
}
如果我们删除节点5(这是由!!标记)的代码工作得很好,否则它给出了一个分段错误。
功能上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;
}
它在哪一行上发生段错误?用'-g'选项编译,然后用corefile:'gdb prog core'启动'gdb',运行'bt'命令 - 它会打印回溯图并且会告诉你程序段错误的确切位置。 – qrdl 2009-12-26 16:17:54
启动程序:/家庭/纳兹米/桌面/符号表/ XX /新/ AST OP 左 - INT - INT:19 计划接收信号SIGSEGV,分割过错。 0x08048891在ast.c中为traverse99(root = 0x11):154 154 if(root-> nodeType == OP) – iva123 2009-12-26 16:57:01
因此它在第154行失败,取消引用'root'。你需要确保在提领之前'root'不是'NULL' – qrdl 2009-12-26 17:28:18