1138 Postorder Traversal (25 分)(cj)

1138 Postorder Traversal (25 分)

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

code

#pragma warning(disable:4996)
#include <iostream>
#include <vector>
#include <stdio.h>
#include <string>
#include <set>
using namespace std;
int inorder[50005];
int preorder[50005];
bool f = 1;
void posttravel(int q, int e, int l, int r);
int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		cin >> preorder[i];
	}
	for (int i = 0; i < n; ++i) {
		cin >> inorder[i];
	}
	posttravel(0, n - 1, 0, n - 1);
	system("pause");
	return 0;
}
void posttravel(int q, int e, int l,int r) {
	if (q > e) return;
	else if (q == e) {
		if (f) {
			cout << inorder[q];
			f = 0;
		}
		return;
	}
	int x = preorder[l];
	int p = 0;
	for (int i = q; i <= e; ++i) {
		if (inorder[i] == x) {
			p = i; break;
		}
	}
	posttravel(q, p - 1, l + 1, l + p - q);
	if (f == 0) return;
	posttravel(p + 1, e, l + p - q + 1, r);
	if (f == 0) return;
	cout << x;
	f = 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章