1
我試圖調用函數buildExpressionTree與字符串「(4 + 5)」 我試圖調試,發現樹已成功創建,但當返回到主,「tr」是空和包含垃圾。 爲什麼它無法返回樹? 請幫忙,謝謝!消失的二叉樹
int main(){
char str[SIZE];
Tree tr;
double res;
BOOL expressionOK;
printf("Please enter the expression: ");
gets(str);
expressionOK = buildExpressionTree(str, &tr);
freeTree(tr);
return 0;
}
這是 「buildExpressionTree」 功能:
BOOL buildExpressionTree(char * str, Tree * tr){
BOOL valid = isvalidString(str);
if (valid){
tr = (Tree *)malloc(sizeof(Tree));
tr->root = buildTree(str, strlen(str));
}
else{
tr = NULL;
}
return valid;
}
,這是遞歸函數創建樹:
TreeNode * buildTree(char * str, int strLength){
int mainOpPlace;
TreeNode * resNode;
//if empty tree
if (strLength < 0){
return NULL;
}
else{
//find the main operator of the current string
mainOpPlace = findMainOperator(str, strLength);
//creating the tree Node
resNode = (TreeNode *)malloc(sizeof(TreeNode));
resNode->data = str[mainOpPlace];
resNode->left = (buildTree(str + 1, mainOpPlace - 1));
resNode->right = (buildTree(str + mainOpPlace + 1, (strLength - mainOpPlace - 2)));
return resNode;
}
}
在您的主函數中,您將tr變量的地址傳遞給buildExpressionTree函數。在那個函數中,你爲樹分配內存,但是你不會傳回它。由於tr參數是一個指向Tree的指針,因此當爲它分配內存時,只需更新函數中的本地tr變量即可。它對主函數的作用域沒有影響。 – OrenD
'Tree'和'TreeNode'的定義是什麼,Tree是一個結構體還是指針? –