1020 Tree Traversals (25分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

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

Sample Output:

4 1 6 3 5 7 2
			
已知中序后序,求二叉树的层次遍历
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 31;
int post[maxn], in[maxn];
struct node
{
	int data;
	node* lchid;
	node* rchid;
};
int n;
node* creat(int pl, int pr, int il, int ir)//中序后序建立二叉树
{
	if (pl > pr)return NULL;
	node* root=new node;
	root->data= post[pr];
	int k;
	for ( k =il; k<=ir; k++)
		if (in[k] == post[pr])
			break;
	int numl = k - il;
	root->lchid = creat( pl, pl + numl - 1, il, k - 1);
	root->rchid = creat(pl + numl, pr - 1, k + 1, ir);
	return root;
}
int num=0;
void BFS(node*root)//层次遍历的广度优先搜索法
{
	queue<node*>q;
	q.push(root);
	while (!q.empty())
	{
		node* T= q.front();
		q.pop();
		cout <<T->data;
		num++;
		if (num != n)
			cout << " ";
		if (T->lchid != NULL)
			q.push(T->lchid);
		if (T->rchid != NULL)
			q.push(T->rchid);
	}
	cout << endl;
}
int main()
{
	FILE* stream1;
	freopen_s(&stream1, "input.txt", "r", stdin);
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> post[i];
	for (int i = 1; i <= n; i++)
		cin >>in[i];
	node* root = creat(1, n, 1, n);
	BFS(root);
	return 0;
}