0

我正在尝试递归地创建一个表达式树。每当这个函数接收到其他表达式变量时,它运行得非常好。但是每当它接收到一个整数(或者在这种情况下是一个将它带到 else 语句的字符串)时,它就会使我的程序崩溃。

     void buildExpressionTree (istream &ins, BinaryNode* p)
     {
         string buffer;

         //read in from file             
         while ((ins.peek()!='\n') && (ins >> buffer))
         {
             if(p == NULL && buffer == "*","/","+","-")
             {
                 p = new BinaryNode(buffer, NULL, NULL);
                 buildExpressionTree(ins,p->left);
                 buildExpressionTree(ins,p->right);
             }
             else 
             {
                 p = new BinaryNode(buffer, NULL, NULL);
             }
        }
      }

p 是树的根(传递给此函数时为 null), ins 是输入文件流对象。

4

1 回答 1

1

很抱歉说它运行不正常,有多个错误

首先

if(p == NULL && buffer == "*","/","+","-")

应该

if(buffer == "*" || buffer == "/" || buffer == "+" || buffer == "-")

逗号无法按照您的预期工作。

其次,如果你想建立你的树,你应该从函数返回一个指针,而不是把一个指针传递给函数。像这样

 BinaryNode* buildExpressionTree (istream &ins)
 {
     string buffer;

     //read in from file    
     BinaryNode* p = NULL;
     while ((ins.peek()!='\n') && (ins >> buffer))
     {
         if(buffer == "*" || buffer == "/" || buffer == "+" || buffer == "-")
         {
             p = new BinaryNode(buffer, NULL, NULL);
             p->left = buildExpressionTree(ins);
             p->right = buildExpressionTree(ins);
         }
         else 
         {
             p = new BinaryNode(buffer, NULL, NULL);
         }
    }
    return p;
}

This seems to be a very common misunderstanding of how pointers work when passed to a function. If you pass a pointer to a function you can use it to modify what is being pointed to in the calling function, you cannot use it to modify the pointer itself in the calling function.

于 2013-10-09T09:05:10.707 回答