B3642 二叉树的遍历(两种实现方法

二叉树的遍历

题目描述

有一个 n ( n ≤ 1 0 6 ) n(n \le 10^6) n(n106) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 n n n),建立一棵二叉树(根节点的编号为 1 1 1),如果是叶子结点,则输入 0 0

建好树这棵二叉树之后,依次求出它的前序、中序、后序列遍历。

输入格式

第一行一个整数 n n n,表示结点数。

之后 n n n 行,第 i i i 行两个整数 l l l r r r,分别表示结点 i i i 的左右子结点编号。若 l = 0 l=0 l=0 则表示无左子结点, r = 0 r=0 r=0 同理。

输出格式

输出三行,每行 n n n 个数字,用空格隔开。

第一行是这个二叉树的前序遍历。

第二行是这个二叉树的中序遍历。

第三行是这个二叉树的后序遍历。

样例 #1

样例输入 #1

7
2 7
4 0
0 0
0 3
0 0
0 5
6 0

样例输出 #1

1 2 4 3 7 6 5
4 3 2 1 6 5 7
3 4 2 5 6 7 1

非主流之yxc插入树(折磨了会脑子)

#include<iostream>
#include<cstring>
using namespace std;
const int N=1000100;
int h[N],ne[N],e[N],idx;

void add(int a,int b){
	e[idx]=b;
	ne[idx]=h[a];
	h[a]=idx;
	idx++;
}

void pre(int x){
	cout<<x<<" ";
	for(int i=h[x];i!=-1;i=ne[i]){
		if(e[i]!=0)pre(e[i]);
	}
}

 
void ino(int x){//最难实现中序,得判断左右和是不是叶节点。
				//t2用于判断叶节点,因为叶节点循环内不可能输出,只能在循坏外补充输出
				//t1用来判断左右叶子,t1=1说明左叶子走过,但是右叶子为0的话也没法输出,所以得用到上面的输出 
	int t1=0;int t2=1;
	for(int i=h[x];i!=-1;i=ne[i]){
		t1++;
		if(e[i]==0)continue;
		if(t1==2){cout<<x<<" ";t2=0;}
		ino(e[i]);
	}
	if(t2)cout<<x<<" ";
}

void post(int x){
	for(int i=h[x];i!=-1;i=ne[i]){
		if(e[i]!=0)post(e[i]);
	}
	cout<<x<<" ";
}

int main(){
memset(h,-1,sizeof h);
int head=1;
int n;cin>>n;

for(int i=1;i<=n;i++){
	int l,r;cin>>l>>r;
	add(i,r);//因为是头插法,所以先插右边在插入左边 
	add(i,l);
}

//for(int i=1;i<=n;i++){
//
//	for(int j=h[i];j!=-1;j=ne[j]){
//		cout<<e[j]<<" ";
//	}
//	cout<<"\n";
//}


pre(head);
cout<<"\n";
ino(head);
cout<<"\n";
post(head);

 

}

日常之结构树

#include<iostream>
#include<cstring>
using namespace std;
const int N=1000100;
struct Tree{
	int l,r;
}tree[N];


void pre(int x){
	cout<<x<<" ";
	int l=tree[x].l;
	int r=tree[x].r;
	if(l)pre(l);
	if(r)pre(r);
}

void ino(int x){
	
	int l=tree[x].l;
	int r=tree[x].r;
	if(l)ino(l);
	cout<<x<<" ";
	if(r)ino(r);
}
void post(int x){
	int l=tree[x].l;
	int r=tree[x].r;
	if(l)post(l);
	if(r)post(r);
	cout<<x<<" ";
}

int main(){

int head=1;
int n;cin>>n;

for(int i=1;i<=n;i++){
	cin>>tree[i].l>>tree[i].r;
}




pre(head);
cout<<"\n";
ino(head);
cout<<"\n";
post(head);

 

}
  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值