【数据结构】二叉树的遍历(前、中、后序遍历)

//代码改编自《挑战程序设计竞赛2》

目标:用三种遍历方式打印出树

由于我想偷懒易于理解我就不注释了

输入样例:

9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1

输出样例:

前序遍历的结果是:
0 1 2 3 4 5 6 7 8
中序遍历的结果是:
2 1 3 0 6 5 7 4 8
后序遍历的结果是:
2 3 1 6 7 5 8 4 0

#include<cstdio>
#include<iostream>
#define MAX 10000
#define NIL -1
using namespace std;

struct node{
	int p,l,r;
};
node t[MAX];
int n;

void preParse(int u){
	if(u==NIL) return;
	cout<<u<<' ';
	preParse(t[u].l);
	preParse(t[u].r);
}

void inParse(int u){
	if(u==NIL) return;
	inParse(t[u].l);
	cout<<u<<' ';
	inParse(t[u].r);	
}

void postParse(int u){
	if(u==NIL) return;
	postParse(t[u].l);
	postParse(t[u].r);
	cout<<u<<' ';
}
int main(){
	int i,v,l,r,root;
	cin>>n;
	for(i=0;i<n;i++)t[i].p=NIL;
	
	for(i=0;i<n;i++){
		cin>>v>>l>>r;
		t[v].l=l;
		t[v].r=r;
		if(l!=NIL)t[l].p=v;
		if(r!=NIL)t[r].p=v;
	}
	
	for(i=0;i<n;i++)if(t[i].p==NIL)root=i;
	
	cout<<"前序遍历的结果是:"<<endl;
	preParse(root);
	cout<<endl; 
	
	cout<<"中序遍历的结果是:"<<endl;
	inParse(root);
	cout<<endl;
	
	cout<<"后序遍历的结果是:"<<endl;
	postParse(root);
	cout<<endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/melon_sama/article/details/108551307