Search code examples
c++recursiontreetostringinorder

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. 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. I know that this means there is something wrong with my recursion, though I cannot seem to pinpoint the error. Thanks in advance.


Solution

  • 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.