树的遍历

树的遍历

树上 \(DFS\):

访问根节点 \(\to\) 访问根节点的每个儿子的子树

可以求出各种有用的信息

二叉树上 \(DFS\):

先序遍历


按照根 \(\to\)\(\to\) 右的顺序遍历。

实现:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10005;
int t[MAXN];
int n,m;
void dfs(int fa){//前序遍历
	if(t[fa] == 0){
		return;
	}
	cout<<char(t[fa]);
	dfs(fa * 2);
	dfs(fa * 2 + 1);
}
int main(){
	//建树:
	t[1] = 'F';t[2] = 'B';t[3] = 'G';t[4] = 'A';t[5] = 'D';t[10] = 'C';t[11] = 'E';t[7] = 'I';t[14] = 'H';
	dfs(1);
	return 0;
}

中序遍历


按照 左 \(\to\)\(\to\) 右 的顺序遍历。

实现:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10005;
int t[MAXN];
int n,m;
void dfs(int fa){//中序遍历
	if(t[fa] == 0){
		return;
	}
	dfs(fa * 2);
	cout<<char(t[fa]);
	dfs(fa * 2 + 1);
}
int main(){
	//建树:
	t[1] = 'F';t[2] = 'B';t[3] = 'G';t[4] = 'A';t[5] = 'D';t[10] = 'C';t[11] = 'E';t[7] = 'I';t[14] = 'H';
	dfs(1);
	return 0;
}

后序遍历


按照 左 \(\to\)\(\to\) 根的顺序遍历。

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10005;
int t[MAXN];
int n,m;
void dfs(int fa){//后序遍历
	if(t[fa] == 0){
		return;
	}
	dfs(fa * 2);
	dfs(fa * 2 + 1);
	cout<<char(t[fa]);
}
int main(){
	//建树:
	t[1] = 'F';t[2] = 'B';t[3] = 'G';t[4] = 'A';t[5] = 'D';t[10] = 'C';t[11] = 'E';t[7] = 'I';t[14] = 'H';
	dfs(1);
	return 0;
}

posted @ 2023-10-13 16:41  wyl123ly  阅读(12)  评论(0)    收藏  举报