Traversing Binary Tree Binary Tree Traversals

 

In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.

 

Input

The input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.

Output

For each test case print a single line specifying the corresponding postorder sequence.

Sample Input

9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6

Sample Output

7 4 2 8 9 5 6 3 1

Preorder traversal order is given and, after seeking preorder.

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
typedef long long ll;
using namespace std;
const ll inf = 1e18;
const int mod = 1000000007;
const int mx = 1e6; //check the limits, dummy
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
#define swa(a,b) a^=b^=a^=b
#define re(i,a,b) for(ll i=(a),_=(b);i<_;i++)
#define rb(i,a,b) for(ll i=(b),_=(a);i>=_;i--)
#define clr(a) memset(a, 0, sizeof(a))
#define lowbit(x) ((x)&(x-1))
#define mkp make_pair
int N;
void ans(int* im1, int* im2, int a, int b, int N, int flag)
{
	if (N == 1)
	{
		printf("%d ",D1 [i]);
		return;
	}
	else if (N == 0) return;
	int i = 0;
	for (; im1[a] != im2[b + i]; i++);
	ans(im1, im2, a + 1, b, i, 0);
	ans(im1, im2, a + i + 1, b + i + 1, N - i - 1, 0);
	if (flag) printf("%d\n", im1[a]);
	else printf("%d ", im1[a]);
}
int main()
{
	while (cin>>N&&N)
	{
		int* im1 = (int*)malloc(sizeof(int) * (N + 2));
		int* im2= (int*)malloc(sizeof(int) * (N + 2));
		for (int i = 1; i <= N; i++) scanf("%d", &im1[i]);
		for (int i = 1; i <= N; i++) scanf("%d", &im2[i]);
		ans(im1, im2, 1, 1, N, 1);
	}
	return 0;
}

  

Guess you like

Origin www.cnblogs.com/xxxsans/p/12669818.html