简体   繁体   English

在递归函数中引发错误

[英]Throwing an error in recursive function

I have a binary tree and in function below, I am printing it out using recursion: 我有一个二叉树,在下面的函数中,我使用递归将其打印出来:

void printTree(node *root){
    if(root!=NULL){
        printTree(root->leftSon);
        cout<<root->key<<" ";
        printTree(root->rightSon);
    }
}

It works fine, but the thing is that I can't find a way to throw an error, when the tree is empty. 它工作正常,但问题是当树为空时,我找不到抛出错误的方法。 I tried to solve this by adding another if statement: 我试图通过添加另一个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);
    }
}

But then again, eventually root will always be set to NULL when it reaches the end of the tree so this function will always throw an error. 但是话又说回来,最终root到达树的末尾时总是将其设置为NULL,因此此函数将始终引发错误。 How can I set a condition to check if root is NULL at the beginning, when the function is first called? 首次调用该函数时,如何设置条件以检查root是否为NULL?

There are multiple ways you could accomplish what you're asking for. 您可以通过多种方式来完成所需的工作。 One of them is: 其中之一是:

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);
}

The intention is that printTree_implementation() can only be called by printTree() , so you know you've got the error checking managed externally to the implementation. 目的是使printTree_implementation() 只能由被称为printTree()所以你知道你有错误检查外部管理来实现。 By making the implementation static, you limit how the function can be called. 通过使实现静态化,可以限制函数的调用方式。

If you were solving this with a class, you would make the implementation a private method. 如果使用类解决此问题,则可以将实现private方法。

There may be some other way but what comes my mind is you can pass some counter variable like 可能还有其他方法,但是我想到的是您可以传递一些计数器变量,例如

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++);
}

The are several ways to do this. 有几种方法可以做到这一点。 Maybe you can try something like this : (not sure if this is the best way) 也许您可以尝试这样的事情:(不确定这是否是最好的方法)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM