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

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

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


1. 全局变量表示
int currentSum = 0;
vector<Node *> path;
void traverse(Node *root, int expectedNum) {
currentSum += root->value;
path.push_back(root);

if(root->left == NULL && root->right == NULL) {
if(currentSum == expectedNum) {
show(path);
cout << currentSum <<endl;
}
}

if(root->left != NULL)
traverse(root->left, expectedNum);
if(root->right != NULL)
traverse(root->right, expectedNum);

[color=red]currentSum -= root->value; // 必须恢复,所有函数调用使用同一个值
path.pop_back();[/color]
}


2. 普通函数参数
void traverse(Node *root, int currentSum, vector<Node *> path, int expectedNum) {
currentSum += root->value;
path.push_back(root);

if(root->left == NULL && root->right == NULL) {
if(currentSum == expectedNum) {
show(path);
cout << currentSum <<endl;
}
}

if(root->left != NULL)
traverse(root->left, currentSum, path, expectedNum);
if(root->right != NULL)
traverse(root->right, currentSum, path, expectedNum);

// 不必恢复 currentSum, path,各函数调用层独立使用
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值