DFS序

DFS序:就是将树形结构转化为线性结构,用dfs遍历一遍这棵树,进入到x节点有一个in时间戳,递归退出时有一个out
时间戳,x节点的两个时间戳之间遍历到的点,就是根为x的子树的所有节点。

问题:求下图的DFS序
DFS序

#include<iostream>
#include<vector>
 
#define max(x,y) (x > y ? x : y)

using namespace std;

int time = 0;

int in[10];
int out[10];
int carr[50];

vector<int> vct[10];

void dfs(int x,int fa){
	in[x] = ++time;
	carr[time] = x;
	for(int i = 0;i < vct[x].size();i++){
		int cnt  = vct[x][i];
		if(cnt == fa){
			continue;
		}
		dfs(cnt,x);
	}
	out[x] = time; 
}

int main(){
	vct[0].push_back(1);
	vct[0].push_back(2);
	vct[1].push_back(3);
	vct[1].push_back(4);
	vct[2].push_back(5);
	vct[2].push_back(6);
	vct[2].push_back(7);
	vct[4].push_back(8);
	dfs(0,-1);
	cout<<"in[]:";
	for(int i = 0;i <10;i++){
		cout<<in[i]<<" ";
	}
	cout<<endl;
	cout<<"out[]:";
	for(int i = 0;i < 10;i++){
		cout<<out[i]<<" "; 
	} 
	cout<<endl;
	cout<<"carr[]:";
	for(int i = 0;i < 20;i++){
		cout<<carr[i]<<" ";
	}
	cout<<endl;
	//求以2为根节点的子树 
	for(int i = in[2]; i <= out[2];i++){
		cout<<carr[i]<<" ";
	}
	return 0;
}