1138 Postorder Traversal (preamble sequence subsequent revolutions)

1138 Postorder Traversal (25 points)

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

Standard preamble sequence in subsequent revolutions:

The only attention is required to optimize the output: since only the output of the first character in claim traversing, the construct without preorder array defining flag = false;

When traversing the first character is a recursion flag = true, when the direct return flag = true, no longer depth of recursion, do not postorder output element other than the first element. (Iterative efficiency should be higher)

#include<iostream>
#include<vector>
using namespace std;
int n;
vector<int> pre, in;
bool flag;
void postOrder(int root, int left, int  right){
	if(left > right || flag == true){     //如果判断的是left == right 就push 因为 i = left 如果 i 直接就是中序最左的元素 i-1就会越界(死循环) 
		return;
	}
	int i = left;
	while(pre[root] != in[i]) i++; 
	postOrder(root + 1, left, i - 1);
	postOrder(root + (i - left) + 1, i + 1, right);
	if(flag == false){
		flag = true;
		printf("%d", pre[root]);
	}
}
int main(){
	scanf("%d", &n);
	pre.resize(n);
	in.resize(n);
	for(int i = 0; i < n; i++){
		scanf("%d", &pre[i]);
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	postOrder(0, 0, n-1);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_41698081/article/details/91635289