[英]Throwing an error in recursive function
我有一个二叉树,在下面的函数中,我使用递归将其打印出来:
void printTree(node *root){
if(root!=NULL){
printTree(root->leftSon);
cout<<root->key<<" ";
printTree(root->rightSon);
}
}
它工作正常,但问题是当树为空时,我找不到抛出错误的方法。 我试图通过添加另一个if语句来解决此问题:
void printTree(node *root) throw(runtime_error){
if(root==NULL) {
throw runtime_error("Tree is empty");
}
if(root!=NULL){
printTree(root->leftSon);
cout<<root->key<<" ";
printTree(root->rightSon);
}
}
但是话又说回来,最终root到达树的末尾时总是将其设置为NULL,因此此函数将始终引发错误。 首次调用该函数时,如何设置条件以检查root是否为NULL?
您可以通过多种方式来完成所需的工作。 其中之一是:
static void printTree_implementation(node *root) {
... do whatever you're already doing without the exception
}
void printTree(node *root) throw(runtime_error){
if(root==NULL) {
throw runtime_error("Tree is empty");
}
printTree_implementation(root);
}
目的是使printTree_implementation()
只能由被称为printTree()
所以你知道你有错误检查外部管理来实现。 通过使实现静态化,可以限制函数的调用方式。
如果使用类解决此问题,则可以将实现private
方法。
可能还有其他方法,但是我想到的是您可以传递一些计数器变量,例如
void printTree(node *root,int counter=0)
{
if(counter==0 && root==NULL)
{
throw runtime_error("Tree is empty");
}
//some other operation
printTree(root->rightSon,counter++);
}
有几种方法可以做到这一点。 也许您可以尝试这样的事情:(不确定这是否是最好的方法)
void printTree(node *root)
{
static int index = 0;
if( 0 == index && !root )
{
throw runtime_error( "Tree is empty" );
}
index++;
if( root )
{
printTree( root->leftSon );
cout << root->key << " ";
printTree( root->rightSon );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.