我想遍歷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