如何停止递归?

abu*_*abu 1 c++ recursion data-structures

下面的代码是to find the path in a tree that adds up to a given sum......我在这里所做的是将enqueue所有节点的值放入一个数组中path,如果条件满足递归,则将其打印......

void checkSum(NODE* root, int path[], int len, int sum){

     if(root == NULL) return;

     path[len] = root->data;
     len++;

     if(sum - root->data == 0){ 
            sum -= root->data;
            cout<<"\nSum equals..."; 
            printPaths(path, len); 
     }
     else if(sum - root->data > 0){
          sum -= root->data;
          checkSum(root->left, path, len, sum);    
          checkSum(root->right, path, len, sum);
     }else { return; }
}
Run Code Online (Sandbox Code Playgroud)

我想知道的是,有没有其他方法可以在不使用任何数据结构的情况下打印路径(至少一个)???

像这样的东西......

void checkSum_second(NODE* root, int sum){

     if(root == NULL) return;

     if(sum - root->data == 0) {  
          //do something
     }     
     else if(sum - root->data > 0){
          sum -= root->data;                 
     }else return;


     checkSum_second(root->left, sum);
     checkSum_second(root->right, sum);     
     cout<<"\nvalue..."<<root->data;
}
Run Code Online (Sandbox Code Playgroud)

考虑一棵树

           1
       2       3
    4    5   6   7
Run Code Online (Sandbox Code Playgroud)

如果sum = 7checkSum_second(root->left, sum);被三次,即执行,直到节点4,在这里,我们是否可以停止一切,只是打印堆栈(即清空)....

das*_*ght 5

要提前终止递归,您需要在调用链上传递某种信号。在您的情况下,您可以将返回类型更改为bool,并返回true以指示搜索已终止,无需进一步处理:

bool checkSum(NODE* root, int path[], int len, int sum) {
     if(root == NULL) return false;
     path[len] = root->data;
     len++;
     if (sum - root->data == 0){ 
          sum -= root->data;
          cout<<"\nSum equals..."; 
          printPaths(path, len);
          return true;
     } else if (sum - root->data > 0) {
          sum -= root->data;
          if (checkSum(root->left, path, len, sum)) {
              return true;
          }
          if (checkSum(root->right, path, len, sum)) {
              return true;
          }
     }
     return false;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在上述代码中,递归调用仅在先前调用继续返回时继续falsetrue从调用返回的第一个被发送到调用链,导致整个调用链终止。