1086. Tree Traversals Again (25)
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;//更新于2017.9.10
int n,s;
vector<int> ino,pre;
stack<int> stk;
void build(int preL,int preR,int inoL,int inoR)
{
if(preL>preR) return;
int e=pre[preL],idx=inoL,pdx=preL;
while(idx<=inoR&&e!=ino[idx]) idx++,pdx++;
build(preL+1,pdx,inoL,idx-1);
build(pdx+1,preR,idx+1,inoR);
++s!=n?cout<<e<<" ":cout<<e;
}
int main()
{
cin>>n;
for(int i=0;i<2*n;++i)
{
string str;
int x;
cin>>str;
if(str=="Push")
{
cin>>x;
pre.push_back(x);
stk.push(x);
}
else
{
ino.push_back(stk.top());
stk.pop();
}
}
build(0,n-1,0,n-1);
return 0;
}
以前AC代码:
博主这里采用了建树的方法
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
struct BTree
{
int data;
struct BTree *lchild,*rchild;
}*T;
int inorder[30+1],preorder[30+1];
int incur,precur,n;
int stack[30+1],top;
void Read(int *c)
{
char s[12];
gets(s);
if(s[1]=='u')
{
char *p=&s[5];
int m=atoi(p);
stack[top++]=m;
preorder[precur++]=m;
}
else
{
(*c)++;
inorder[incur++]=stack[--top];
}
}
void creatBT(int begin,int end,struct BTree **T)
{
if(begin>end)
return;
int root=begin;
int e=preorder[precur++];
(*T)=(struct BTree*)malloc(sizeof(struct BTree));
(*T)->data=e;
(*T)->lchild=(*T)->rchild=NULL;
while(root<=end&&e!=inorder[root])
++root;
creatBT(begin,root-1,&(*T)->lchild);
creatBT(root+1,end,&(*T)->rchild);
}
void PostTraverse(struct BTree *T)
{
if(T)
{
PostTraverse(T->lchild);
PostTraverse(T->rchild);
printf("%d",T->data);
if(--n)printf(" ");
}
}
int main()
{
int c=0;
scanf("%d",&n);
getchar();
while(c<n)
Read(&c);
precur=0;
creatBT(0,n-1,&T);
PostTraverse(T);
return 0;
}
不建树的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int inorder[30+1],preorder[30+1];
int incur,precur,n;
int stack[30+1],top;
void Read(int *c)
{
char s[12];
gets(s);
if(s[1]=='u')
{
char *p=&s[5];
int m=atoi(p);
stack[top++]=m;
preorder[precur++]=m;
}
else
{
(*c)++;
inorder[incur++]=stack[--top];
}
}
void display(int begin,int end)
{
if(begin>end)
return;
int root=begin;
int e=preorder[precur++];
while(root<=end&&e!=inorder[root])
++root;
display(begin,root-1);
display(root+1,end);
printf("%d",e);
if(--n)printf(" ");
}
int main()
{
int c=0;
scanf("%d",&n);
getchar();
while(c<n)
Read(&c);
precur=0;
display(0,n-1);
return 0;
}