7-4 树的遍历 (20分) 给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。 输入格式: 输入第一行给出一个正整数N(≤30),是二叉树中结点的个数

#include <bits/stdc++.h>
using namespace std;
typedef struct TreeNode {
	int data;
	struct TreeNode *lchild,*rchild;
}BTnode,*BTtree; 
int ino[50],post[50];//定于全局变量
BTtree Creattree(int root,int start,int end);
void BLtree(BTtree bt);
int main(){
	int N; cin>>N;
	int i; BTtree bt; 
	for(i=0;i<N;i++){
		int x; cin>>x;
		post[i] = x;
	}
	for(i=0;i<N;i++){
		int x; cin>>x;
		ino[i] = x;
	}
	bt = Creattree(N-1,0,N-1);
	BLtree(bt);
	return 0;
} 

BTtree Creattree(int root,int start,int end){ //后序中序还原二叉树
    BTtree bt;
	if(start>end) return NULL;
	int i;
	for(i=start;post[root]!=ino[i];i++);
	bt = new BTnode;
	bt->data = post[root];
	bt->lchild = Creattree(root-(end-i)-1,start,i-1);
	bt->rchild = Creattree(root-1,i+1,end);
	return bt;
}
void BLtree(BTtree bt){       //层次遍历
	if(bt == NULL) return NULL;
	int flag=0; 
	BTtree queue[50];
	int front =-1; int rear = 0;
	queue[rear] = bt;
	while(front!=rear){
		front++;//保证输出的第一个数之前没有空格
		if(flag++) cout<<" ";
		cout<<queue[front]->data;
		
		if(queue[front]->lchild != NULL){
			rear++;
			queue[rear]  = queue[front]->lchild ;
		}
		if(queue[front]->rchild != NULL) {
			rear++;
			queue[rear]=queue[front]->rchild ;
		}
	}
}
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值