samedi 15 janvier 2022

how to create a c++ recursive function to return a node custom object?

how are you?

I created a C++ recursive function in order to iterate over a binary tree and print out all the NODEs where the property COMPLETED = TRUE;

It´s working pretty fine because the type of the function is VOID and I am only printing out the result.

This is the way that works fine:

void findAndPrintFirstCompletedNodes(treeNode *lastNode) {
     if (lastNode == 0){
         return;
     }
     
   if (lastNode->completed == true) {
          cout << lastNode->word.morseWordElement << endl;
   
   }
      findAndPrintFirstCompletedNodes(lastNode->left);
      findAndPrintFirstCompletedNodes(lastNode->right);
   
 }

But what I want to do is to return the first found "COMPLETED" node instead of just printing!

I tried this way but is not working:

treeNode * findAndPrintFirstCompletedNodes(treeNode *lastNode) {
      if (lastNode == 0){
          return 0;
      }
      
    if (lastNode->completed == true) {
           return lastNode;
    
    }
       findAndPrintFirstCompletedNodes(lastNode->left);
       findAndPrintFirstCompletedNodes(lastNode->right);
    
  }

Thanks for the help.

Filipe

Aucun commentaire:

Enregistrer un commentaire