03-树3 Tree Traversals Again (25 分)

03-树3 Tree Traversals Again (25 分)

 03-树3 Tree Traversals Again (25 分)

大致思路:根据已知条件构建树,构建完成后,采用后序递归遍历树

#include<cstdio>
#include<stack>
#include<string>
#include<iostream>
const int maxn=35;
using namespace std;
struct TNode{
	int left, right;
}T[maxn];
int count=0, n;
void print(int root){
	if(root==-1)return ;
	if(T[root].left!=-1)print(T[root].left);
	if(T[root].right!=-1)print(T[root].right);
	count++;
	printf("%d", root);
	if(count<n/2)printf(" ");
} 
int main(){
	int  num, cnt=0, temp, root, flag=0, first;
	scanf("%d\n", &n);
	for(int i=1; i<=n; i++){//注意题目说角标是从1开始的
		T[i].left=-1;
		T[i].right=-1;
	}
	n=n*2;
	string s;
	stack<int> st;
	for(int i=0; i<n; i++){
		cin>>s;
		if(s=="Push"){
			cin>>num;
			st.push(num);
			if(i==0){
				root=num;
				first=num;
			}else{
				if(flag==0)T[root].left=num;
				else T[root].right=num;
				root=num;
				flag=0;
			}
		}else{
			root=st.top();
			st.pop();
			flag=1;
		}
	} 
	print(first);
	return 0;
}