简体   繁体   中英

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:

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. How can I set a condition to check if root is NULL at the beginning, when the function is first called?

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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