---
title: "递归调用中使用全局变量和函数参数之间的差异"
author: "William_Third"
date: "2013-04-27T16:31:50Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-04-27T16:31:50Z"
id: 1856108
url: "https://william-third.iteye.com/blog/1856108"
---

对树、图进行 遍历时，包括 前序、中序、后序、深度搜索、广度搜索

存在一些参数，可以用
    1.  全局变量表示，递归结束后必须对该变量修改，恢复原值
    2.  普通函数参数，因为递归调用函数时，实际上，从内存分布上看，每一层调用都保存了该层函数的参数，因此递归返回上层时，不会影响原参数值


1.   全局变量表示

```c++
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. 普通函数参数

```c++
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，各函数调用层独立使用
}
```