PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历)

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

我树方面的题好菜啊…这两天去搭自己的博客网站了所以更新少,网站搭到一半不想搭了,完全是不会前端…毕竟也没学过不是…

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;
}
PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历)PAT_Advanced Level_1020 Tree Traversals(C++_二叉树遍历) ccql 发布了253 篇原创文章 · 获赞 31 · 访问量 1万+ 私信 关注
上一篇:Java实现 LeetCode 653 两数之和 IV - 输入 BST(递归,找差值)


下一篇:刷题105. Construct Binary Tree from Preorder and Inorder Traversal