1. 程式人生 > >pat1086 Tree Traversals Again

pat1086 Tree Traversals Again

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
#include<cmath>
#include<map>
#include<stack>
#define ll long long
using namespace std;
int rt;
struct node
{
	int ls,rs;
	node()
	{
		ls = rs = 0;
	}
}tree[50];
stack<int>s;
void Traversal(int u)
{
	if(tree[u].ls)Traversal(tree[u].ls);
	if(tree[u].rs)Traversal(tree[u].rs);
	if(u!=rt)printf("%d ",u);
	else printf("%d\n",u);
}
int main()
{
	int n,i,j,f,now;
	char op[10];
	while(scanf("%d",&n)!=EOF)
	{
		rt = f = 0;
		for(i = 1;i<=2*n;i++)
		{
			scanf("%s",op);
			if(op[1] == 'u')
			{
				int x;
				scanf("%d",&x);
				if(rt == 0)rt = x;
				else 
				{
					if(!f)tree[now].ls = x;
					else tree[now].rs = x;
					f = 0;
				}
				s.push(x);
				now = x;
			}
			else
			{
				int u = s.top();
				now = u;
				s.pop();
				f = 1;
			}
		}
		Traversal(rt);
	}
    return 0;
}