3143 二叉树的序遍历

Posted Code_Together

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3143 二叉树的序遍历相关的知识,希望对你有一定的参考价值。

题目描述 Description

求一棵二叉树的前序遍历,中序遍历和后序遍历

输入描述 Input Description

第一行一个整数n,表示这棵树的节点个数。

接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。

输出描述 Output Description

输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。

样例输入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

样例输出 Sample Output

1 2 4 5 3

4 2 5 1 3

4 5 2 3 1

数据范围及提示 Data Size & Hint

n <= 16

 

#include<cstdio>
#include<algorithm>
using namespace std;
struct Node{int No,L,R;}a[1000];

void pre_DFS(int i){
	printf("%d ",i);
	if(a[i].L)pre_DFS(a[i].L);
	if(a[i].R)pre_DFS(a[i].R);
}
void in_DFS(int i){
	if(a[i].L)in_DFS(a[i].L);
	printf("%d ",i);
	if(a[i].R)in_DFS(a[i].R);
}
void post_DFS(int i){
	if(a[i].L)post_DFS(a[i].L);
	if(a[i].R)post_DFS(a[i].R);
	printf("%d ",i);
}
int main(){
	int n,i;
	scanf("%d",&n);
	for(i=1;i<=n;i++){a[i].No=i;scanf("%d%d",&a[i].L,&a[i].R);}
	pre_DFS(1); puts("");
	in_DFS(1); puts("");
	post_DFS(1); puts("");
	return 0;
}

以上是关于3143 二叉树的序遍历的主要内容,如果未能解决你的问题,请参考以下文章

3143 二叉树的序遍历

3143 二叉树的序遍历codevs

codevs3143 二叉树的序遍历

3143 二叉树的序遍历——http://codevs.cn/problem/3143/

3143 二叉树的序遍历

3143 codevs 二叉树的序遍历