我有一个二叉树,在下面的函数中,我使用递归将其打印出来:
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)
方法。
关于c++ - 递归函数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22561087/