PAT_Advanced Level_1020 Tree Traversals (C ++ _ binary tree traversal)

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 (≤30), 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

Process

My tree aspects of the question of good food ah ... two days to take his own blog site so little updated, the site did not want to take a ride to a half, is not entirely the front ... after all, never learned not ...

Code

#include<bits/stdc++.h>
using namespace std;
#define MAX 10010
int n, cnt;
int post[MAX], inorder[MAX], ans[MAX];
void tree(int start, int end, int root, int index)
{
	if (start > end)
		return;
	int k = end;
	ans[index] = post[root];
	for (int i = start; i < end; i++)
		if (inorder[i] == post[root])
		{
			k = i;
			break;
		}
	tree(start, k - 1, root - (end - k + 1), index * 2 + 1);
	tree(k + 1, end, root - 1, index * 2 + 2);
}
int main()
{
	memset(ans, -1, sizeof(ans));
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> post[i];
	for (int i = 0; i < n; i++)
		cin >> inorder[i];
	tree(0, n - 1, n - 1, 0);
	for (int i = 0; i < MAX; i++)
	{
		if (ans[i] != -1)
			cout << ans[i] << (++cnt == n ? "\n" : " ");
		if (cnt == n)
			break;
	}
	return 0;
}
Published 253 original articles · won praise 31 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43510916/article/details/104486454