C++ 中的非递归树
Non recursive tree in c++?
我找到了一个用 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
}
如果您真的想使它非递归,请自己实现一个堆栈并使用此堆栈而不是递归。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 使用递归时获取变量的奇怪值
- 如何在C++中递归地按相反顺序打印集合
- 到连接组件算法的问题(递归)
- 如何使用递归打印修改后的星号三角形图案
- 使用递归模板动态分配的多维数组
- 递归函数有效,但无法记忆
- 包含模板文件的递归会导致编译失败