跳到正文

个人记录

【模板】树的dfs序&&树的欧拉序

Zyh_AKer约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年7月15日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 5 分钟

版本

  1. v1当前

树的dfs序

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
int n;
int a[N],tree[N<<2];
void dfs1(int root)
{
	if (root)
	{
		cout<<root<<" ";
		dfs1(tree[root<<1]);
		dfs1(tree[root<<1|1]);
	}
}
void dfs2(int root)
{
	if (root)
	{
		dfs2(tree[root<<1]);
		cout<<root<<" ";
		dfs2(tree[root<<1|1]);
	}
}
void dfs3(int root)
{
	if (root)
	{
		dfs3(tree[root<<1]);
		dfs3(tree[root<<1|1]);
		cout<<root<<" ";
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for (int i=1;i<=n;i++)
	{
		cin>>a[i];
		if (a[i]!=i)
		{
			if (!tree[a[i]<<1])
			{
				tree[a[i]<<1]=i;
			}
			else
			{
				tree[a[i]<<1|1]=i;
			}
		}
	}
	dfs1(1);
	cout<<endl;
	dfs2(1);
	cout<<endl;
	dfs3(1);
	return 0;
}
C++
#include<bits/stdc++.h>
using namespace std;
int n;
vector<int>ve[10005];
int dfs_order[10005];
int pos;
bool vis[10005];
void dfs(int root)
{
	dfs_order[++pos]=root;
	vis[root]=true;
	for (int i=0;i<ve[root].size();i++)
	{
		if (!vis[ve[root][i]])dfs(ve[root][i]);
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for (int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		ve[x].push_back(y);
		ve[y].push_back(x);
	}
	dfs(1);
	for (int i=1;i<=pos;i++)
	{
		cout<<dfs_order[i]<<" ";
	}
	return 0;
}

树的欧拉序1

C++
#include<bits/stdc++.h>
using namespace std;
int n;
vector<int>ve[10005];
int dfs_order[10005];
int pos;
bool vis[10005];
void dfs(int root)
{
	dfs_order[++pos]=root;
	vis[root]=true;
	for (int i=0;i<ve[root].size();i++)
	{
		if (!vis[ve[root][i]])
		{
			dfs(ve[root][i]);
			dfs_order[++pos]=root;
		}
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for (int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		ve[x].push_back(y);
		ve[y].push_back(x);
	}
	dfs(1);
	for (int i=1;i<=pos;i++)
	{
		cout<<dfs_order[i]<<" ";
	}
	return 0;
}

树的欧拉序2

C++
#include<bits/stdc++.h>
using namespace std;
int n;
vector<int>ve[10005];
int dfs_order[10005];
int pos;
bool vis[10005];
void dfs(int root)
{
	dfs_order[++pos]=root;
	vis[root]=true;
	for (int i=0;i<ve[root].size();i++)
	{
		if (!vis[ve[root][i]])
		{
			dfs(ve[root][i]);
		}
	}
	dfs_order[++pos]=root;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for (int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		ve[x].push_back(y);
		ve[y].push_back(x);
	}
	dfs(1);
	for (int i=1;i<=pos;i++)
	{
		cout<<dfs_order[i]<<" ";
	}
	return 0;
}
原文