在编写递归函数时,我们可以选择使用全局变量,也可以选择使用函数参数。这两者的差别在于:
- 全局变量的形式,递归结束后必须对该变量修改,恢复原值;
- 函数参数的形式,因为递归调用函数时,实际上,从内存分布上看,每一层调用都保存了该层函数的参数,因此递归返回上层时,不会影响原参数值。
拿一道题举例,求二叉树中和为某一值的路径:
全局变量的写法:
int currentSum = 0;
vector<Node *> path;
void traverse(Node *root, int expectedNum) {
if(root==NULL) return;
currentSum += root->value;
path.push_back(root);
//如果是叶节点,并且路径上结点的和等于输入的值
if(root->left == NULL && root->right == NULL) {
if(currentSum == expectedNum) {
show(path);
cout << currentSum <<endl;
}
}
traverse(root->left, expectedNum);
traverse(root->right, expectedNum);
currentSum -= root->value; // 必须恢复,所有函数调用使用同一个值
path.pop_back();[/color]
}
普通的函数参数的写法:
void traverse(Node *root, int currentSum, vector<Node *> path, int expectedNum) {
if(root==NULL) return;
currentSum += root->value;
path.push_back(root);
//如果是叶节点,并且路径上结点的和等于输入的值
if(root->left == NULL && root->right == NULL) {
if(currentSum == expectedNum) {
show(path);
cout << currentSum <<endl;
}
}
traverse(root->left, currentSum, path, expectedNum);
traverse(root->right, currentSum, path, expectedNum);
// 不必恢复 currentSum, path,各函数调用层独立使用
}
当使用的函数参数为引用形参时,由于是对每层递归都是使用同一个变量,所以效果上类似于使用全局变量。其返回上层递归时,也必须恢复现场。