1020

#include<iostream>
#include<queue>
using namespace std;
typedef struct BNode
{
	int data;
	struct BNode *Left;
	struct BNode *Right;
}BNode, *BTree;

void Solve(int Lev[100],int n,int Post[100],int In[100]);
int Find(int In[100], int f, int h, int Post[100],int n);
void Creat(int f, int h, int In[100], int Post[100], int n, BTree &BT);
void PostOrder(BTree BT);
void PreOrder(BTree BT);
int main()
{
	int n;
	int Post[100];
	int In[100];
	int Lev[100];
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> Post[i];
	for (int i = 0; i < n; i++)
		cin >> In[i];
	Solve(Lev, n, Post, In);

	system("pause");
	return 0;
}
void Solve(int Lev[100],int n,int Post[100],int In[100])
{
	BTree BT;
	Creat(0, n - 1, In, Post, n, BT);
	//PostOrder(BT);
	//PreOrder(BT);
	queue<BTree> S;
	S.push(BT);
	int c = 0;
	while (!S.empty())
	{
		BTree P = S.front();
		S.pop();
		Lev[c++] = P->data;
		if(P->Left!=NULL)
			S.push(P->Left);
		if(P->Right!=NULL)
			S.push(P->Right);
	}
	for (int i = 0; i < n; i++)
	{
		if (i == 0)
			cout << Lev[i];
		else
			cout << ' ' << Lev[i];
	}
	cout << endl;
}
void PostOrder(BTree BT)
{
	if (BT != NULL)
	{
		PostOrder(BT->Left);
		PostOrder(BT->Right);
		cout << BT->data << ' ';
	}
}
void PreOrder(BTree BT)
{
	if (BT != NULL)
	{
		cout << BT->data << ' ';
		PreOrder(BT->Left);
		PreOrder(BT->Right);
		
	}
}
void Creat(int f, int h,int In[100],int Post[100],int n,BTree &BT)
{
	int pos=Find(In, f, h, Post, n);
	BT = new BNode();
	BT->data = In[pos];
	//cout << In[pos] << ' ';
	BT->Left = BT->Right = NULL;
	if(f<pos)
		Creat(f, pos-1, In, Post, n, BT->Left);
	if(h>pos)
		Creat(pos+1, h, In, Post, n, BT->Right);
}
int Find(int In[100], int f, int h, int Post[100],int n)
{
	int MaxPos = 0;
	int pos = f;
	for (int i = f; i <= h; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (In[i] == Post[j] && j > MaxPos)
			{
				MaxPos = j;
				pos = i;
			}
		
		}
	}
	return pos;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值