1119 Pre- and Post-order Traversals

The title sequence and the first sequence postorder traversal sequence is converted into a sequence, as in the form of still traversal sequence, first the left subtree, the root node of the output, then the right subtree. But for in.push_back (pre [preL]); the same time I print this value in this position, can only get three results, this is why.
After the first-order traversal sequence in order still need to summarize

#include <iostream>
#include <vector>
using namespace std;
const int maxn = 40;
vector<int> in;
bool isuniq = true;
int pre[maxn], post[maxn];
void getin(int preL, int preR, int posL, int posR){
	if(preL == preR){
		in.push_back(pre[preL]); return;
	}
	int i = preL + 1;
	while(pre[i] != post[posR - 1] && i <= preR) i++;
	if(i - preL > 1) getin(preL + 1, i - 1, posL, posL + i - 2 - preL);
	else isuniq = false;
	in.push_back(pre[preL]);
	getin(i, preR, posL + i - preL - 1, posR - 1);
}
int main(){
	int n; cin >> n;
	for(int i = 0; i < n; i++) cin >> pre[i];
	for(int i = 0; i < n; i++) cin >> post[i];
	getin(0, n - 1, 0, n - 1);
	printf("%s", isuniq?"Yes\n" : "No\n");
	for(int i = 0; i < in.size(); i++)
		printf("%s%d", i == 0? "":" ", in[i]);
    printf("\n");
}
Published 163 original articles · won praise 0 · Views 1586

Guess you like

Origin blog.csdn.net/weixin_35737222/article/details/104089017