简体   繁体   English

为了toString函数C ++的二叉树

[英]Binary Tree in order toString function C++

I've been having trouble with this function for awhile now, partly because there are restrictions by this assignment on how I have to implement a toString method. 我使用此函数已有一段时间了,部分原因是此分配对我必须实现toString方法的方式有所限制。 I have the original method that creates a result string, then sets it equal to a method that is supposed to return a string of the binary tree in order. 我有创建结果字符串的原始方法,然后将其设置为等于应该按顺序返回二叉树字符串的方法。 I have provided the code below: 我提供了以下代码:

string Expression::toString() const{
    string result = "";
    result = inOrder(root, result);
    return result;
}

string Expression::inOrder(Node* r, string x) const{
  if(r->right==NULL && r->left == NULL){
    if(r->num != NULL){
        x += "(";
        char c = r->num + '0';
        string y(1, c);
        x += y;
        x += ")";
    } else{
        x += "(";
        x += r->op;
        x += ")";
    }
    return x;
   }
  x+=inOrder(r->left, x);
  x+=r->op;
  x+=inOrder(r->right, x);
}

Since the constant functions cannot manipulate any outside variables, my tactic was to pass a string parameter in the recursive helper function that would append the nodes as it passed them, and then finally return that string. 由于常量函数无法操纵任何外部变量,因此我的策略是在递归帮助器函数中传递一个字符串参数,该参数将在传递节点时附加节点,然后最终返回该字符串。 However, I've encountered an "access violation reading location 0xcccccccc" error. 但是,我遇到了“访问冲突读取位置0xcccccccc”错误。 I know that this means there is something wrong with my recursion, though I cannot seem to pinpoint the error. 我知道这意味着我的递归有问题,尽管我似乎无法查明错误。 Thanks in advance. 提前致谢。

You only handled two cases, (r->right==NULL && r->left == NULL) and (r->right!=NULL && r->left != NULL) out of 4 possible cases correctly. 您只正确处理了4种可能情况中的两种情况(r->right==NULL && r->left == NULL)(r->right!=NULL && r->left != NULL) That is, if exactly one of r->left and r->right equals to NULL , your program crashes. 也就是说,如果r->leftr->right一个恰好等于NULL ,则程序将崩溃。

You didn't take into consideration the single-child case. 您没有考虑到独生子女的情况。 If either r->left is NULL or r->right is NULL , you will be accessing a NULL pointer. 如果任一r->leftNULLr->rightNULL ,您将访问一个NULL指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM