【问题标题】:Disappearing binary Tree消失的二叉树
【发布时间】:2015-08-05 23:06:26
【问题描述】:

我试图用字符串“(4+5)”调用函数buildExpressionTree 我尝试调试,发现树创建成功,但是当返回主目录时,“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 函数。在该函数中,您为 Tree 分配内存,但不将其传回。由于 tr 参数是一个指向 Tree 的指针,因此在为它分配内存时,只需更新函数中的本地 tr 变量即可。它对 main 函数的作用域没有影响。
  • TreeTreeNode的定义是什么,Tree是结构体还是指针?

标签: c struct binary-tree dynamic-allocation


【解决方案1】:

你需要 buildExpressionTree() 来返回 malloc 分配的树内存的地址。您可以通过将函数键入为 Tree* 来做到这一点,将 bool 参数的返回移动到参数列表中

Tree *buildExpressionTree(char * str, BOOL * AddressOfExpressionOK ) { ..

或者你可以在参数列表中返回它,将树指针的值放在调用者提供的地址上,作为指向树的指针,

BOOL buildExpressionTree(char * str, Tree **ptr){ ..

但我认为另一种方法更容易阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2017-04-14
    • 2011-09-16
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多