欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1138 Postorder Traversal

程序员文章站 2024-01-11 23:20:11
...

1138 Postorder Traversal
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder 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 (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder 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 first number of the postorder traversal sequence of the corresponding binary tree.

Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
由前序和中序转后序
参考代码:

#include<iostream>
#include<vector>
using namespace std;
vector<int>preOrder, inOrder;
int flag = 1;
void solve(int root, int inl, int inr) {
	if (inl >= inr)
		return;
	int i = inl;
	while (i < inr&&inOrder[i] != preOrder[root]) { i++; }
	int l = i - inl;
	solve(root + 1, i - l, i);
	solve(root + 1 + l, i + 1, inr);
	if (flag) {
		cout << preOrder[root];
		flag = 0;
	}
}
int main(){
	int n;
	scanf_s("%d", &n);
	preOrder.resize(n);
	inOrder.resize(n);
	for(int i = 0; i<n; i++)  scanf_s("%d",&preOrder[i]);
	for(int i = 0; i<n; i++)  scanf_s("%d", &inOrder[i]);
	solve(0, 0, n);
	return 0;
}