C++ 中的非递归树

Non recursive tree in c++?

本文关键字:递归 C++      更新时间:2023-10-16

我找到了一个用 c++ 制作表达式树的好网站。getValue函数对我来说非常有意义,但是有没有办法使其非递归?否则它可能会造成堆栈溢出,对吗?

double getValue( ExpNode *node ) { // Return the value of the expression represented by // the tree to which node     refers. Node must be non-NULL. 
    if ( node->kind == NUMBER ) { // The value of a NUMBER node is the number it holds. 
        return node->number; 
    }
    else { // The kind must be OPERATOR. // Get the values of the operands and combine them 
          // using the operator. 
       double leftVal = getValue( node->left )
       double rightVal = getValue( node->right ); 
       switch ( node->op ) {
       case '+': return leftVal + rightVal; 
       case '-': return leftVal - rightVal; 
       case '*': return leftVal * rightVal; 
       case '/': return leftVal / rightVal;
       } 
    }
} // end getValue()

No.它将引发segmentation fault错误,因为没有NULL检查。如果node NULL并且您正在访问node->kind怎么办?

因此,首先检查node是否NULL。然后做剩下的。

double getValue( ExpNode *node ) {
    if (node==NULL)
        return (double)INT_MAX; //include limits.h and don't use the value INT_MAX in any node
    //rest code
}

如果您真的想使它非递归,请自己实现一个堆栈并使用此堆栈而不是递归。