|
发表于 2019-3-18 13:56:41
|
显示全部楼层
递归是二叉树遍历的常用方法。常见于树控件,骨骼动画,文件夹遍历等。以文件夹遍历示例,举一反三。
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <io.h>
using namespace std;
void listFiles(const char * dir);
int main()
{
char *dir = ".";
cout << "当前文件夹内子目录文件列表" << endl;
listFiles(dir);
return 0;
}
void listFiles(const char * dir)
{
#define MAX_PATH 260
char path[MAX_PATH];
sprintf_s(path, MAX_PATH, "%s\\*.*", dir);
intptr_t handle;
_finddata_t findData;
handle = _findfirst(path, &findData);
if (handle == -1) return;
do
{
if (findData.attrib & _A_SUBDIR)
{
if (strcmp(findData.name, ".") != 0 && strcmp(findData.name, "..") != 0)
{
sprintf_s(path, MAX_PATH, "%s\\%s", dir, findData.name);
cout << "目录" << path << endl;
listFiles(path);
}
}
else {
cout << "文件" << dir << "\\" << findData.name << " " << findData.size << "字节" << endl;
}
} while (_findnext(handle, &findData) == 0);
_findclose(handle);
}
要点: 1.递归是对同名函数反复调用。每次调用结束返回到调用该函数的下一句,不会到同一地址。
调用前地址入栈保护。
2.虽是同名函数,但函数内参数是不同,分别保存在不同地址的栈中。只要没结束,不会冲掉。
比如上述dir,path。看起来是一样,实际上是互不影响的多个同名变量。

|
|