分享

递归调用中使用全局变量和函数参数之间的差异

 guitarhua 2016-05-30
对树、图进行 遍历时,包括 前序、中序、后序、深度搜索、广度搜索

存在一些参数,可以用
    1.  全局变量表示,递归结束后必须对该变量修改,恢复原值
    2.  普通函数参数,因为递归调用函数时,实际上,从内存分布上看,每一层调用都保存了该层函数的参数,因此递归返回上层时,不会影响原参数值


1.   全局变量表示
C++代码  收藏代码
  1. int currentSum = 0;  
  2. vector<Node *> path;  
  3. void traverse(Node *root, int expectedNum) {  
  4.         currentSum += root->value;  
  5.     path.push_back(root);  
  6.       
  7.     if(root->left == NULL && root->right == NULL) {  
  8.         if(currentSum == expectedNum) {  
  9.             show(path);  
  10.             cout << currentSum <<endl;  
  11.         }  
  12.     }  
  13.   
  14.     if(root->left != NULL)  
  15.         traverse(root->left, expectedNum);  
  16.     if(root->right != NULL)  
  17.         traverse(root->right, expectedNum);  
  18.   
  19.     [color=red]currentSum -= root->value;   // 必须恢复,所有函数调用使用同一个值  
  20.     path.pop_back();[/color]  
  21. }  


2. 普通函数参数
C++代码  收藏代码
  1. void traverse(Node *root, int currentSum, vector<Node *> path, int expectedNum) {  
  2.         currentSum += root->value;  
  3.     path.push_back(root);  
  4.       
  5.     if(root->left == NULL && root->right == NULL) {  
  6.         if(currentSum == expectedNum) {  
  7.             show(path);  
  8.             cout << currentSum <<endl;  
  9.         }  
  10.     }  
  11.   
  12.     if(root->left != NULL)  
  13.         traverse(root->left, currentSum, path, expectedNum);  
  14.     if(root->right != NULL)  
  15.         traverse(root->right, currentSum, path, expectedNum);  
  16.   
  17.         // 不必恢复  currentSum, path,各函数调用层独立使用  
  18. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多