c++ - 递归函数抛出错误

标签 c++ error-handling binary-tree

我有一个二叉树,在下面的函数中,我使用递归将其打印出来:

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/

相关文章:

c++ - C++ 是否提供了一种无需范围解析运算符即可访问类中类的方法?

web-services - 您可以将错误视为 RESTful API 中的资源吗?

java - 找不到类 'org.apache.http.entity.mime.content.Filebody',从方法中引用

c++ - 这是使用宏的好方法吗?

c++ - 这个 vector 类中的这个参数是什么?

python - 无法在 Visual Studio Code 中调试 Flask 应用程序

data-structures - 为什么我们需要一个单独的数据结构(例如B-Tree)用于数据库和文件系统?

java - 如何在 BST 中实现删除代码?

algorithm - 证明: Every absolute binary tree can represent a Huffman series

c++ - 如何为包含 int vector 的结构定义 less 运算符