根据中序和后序遍历推导层次遍历

输入:总的结点个数n
中序序列
后序序列
输出:层次遍历序列
注意输出的最后没有空格

测试样例:
输入:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出:
4 1 6 3 5 7 2

总体思路:两个序列的输入,创建树,层次遍历树

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

const int MAX=50;
struct Node 
{
	int val; 
	Node* lchild;
	Node* rchild;
	Node(int a)
	{
		val=a;
		lchild=NULL;
		rchild=NULL;
	}
	Node()
	{
		val=0;
		lchild=NULL;
		rchild=NULL;
	}
};
int in[MAX],post[MAX];
int n;


//传入后序序列及其起始坐标,中序序列及其起始坐标,总的结点数 
Node* createTree(int post[],int i,int in[],int j,int n)
{
	Node* t;
	int ch;
	int p,k;
	if(n<=0) return NULL;
	ch=post[i+n-1];//根结点 
	t=new Node(ch);
	p=j;//临时记录头结点位置 
	while(p<j+n)//寻找根结点 
	{
		if(in[p]==ch)
		break;
		p++;
	}
	k=p-j;//左子树的长度 
	t->lchild=createTree(post,i,in,j,k);
	t->rchild=createTree(post,i+k,in,p+1,n-k-1);
	return t;
	
} 

void BFS(Node* root)
{
	int num=0;//用来记录当前的结点的个数,作用是确保输出的最后没有空格 
	queue<Node*> q;
	q.push(root);
	while(!q.empty())
	{
		Node* now=q.front();
		q.pop();
		cout<<now->val;
		num++;
		if(num<n) cout<<" ";//确保最后一个输出的后面没有空格 
		if(now->lchild) q.push(now->lchild);
		if(now->rchild) q.push(now->rchild);
	}
}

int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>post[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>in[i];
	}
	Node* root=createTree(post,0,in,0,n);
	BFS(root);
	return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值