PAT程序设计考题——甲级1086( The best rank ) C++实现

来源:互联网 发布:存在主义心理治疗 知乎 编辑:程序博客网 时间:2024/06/11 02:17
    点击打开链接       
#include<iostream>
#include<math.h>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<vector>
using namespace std;
#define INF 100000000
#define maxn 100010
struct node{
 int id;
 node* lchild;
 node* rchild;
};
node* newnode(node *&root,int id)
{ root=new node;
root->id=id;
root->lchild=NULL;
root->rchild=NULL;
 return root;}
 int pre[maxn],in[maxn],post[maxn];
node* create(int inl,int inr,int prel,int prer)//这个递归的特点就是看起来好像没有return的条件
{
 if(prel>prer) return NULL;//注意返回条件
node *root=new node;
root->id=pre[prel];
int i;
for( i=inl;i<=inr;i++)
if(in[i]==pre[prel])  break;
int numl=i-inl;
root->lchild=create(inl,i-1,prel+1,prel+numl);
root->rchild=create(i+1,inr,prel+numl+1,prer);
return root;//注意一定要返回
}int num;
int time1=0;
void posttra(node *root)
{ if(root==NULL) return;
posttra(root->lchild);
posttra(root->rchild);
cout << root->id;
time1++;
if(time1<num) cout<<" ";
 } 

int main()
{
cin>>num;
string a;
stack<int> s;
int x,preindex=0,inindex=0;//入栈元素 先序序列位置及中序遍历位置
for(int i=0;i<2*num;i++)
{ cin>>a;
if(a.find("Push")==0 )
{  cin>>x;
pre[preindex++]=x;
s.push(x);
}
else {
 in[inindex++]=s.top();
s.pop();
}
}
node *root;
root=create(0,num-1,0,num-1);
posttra(root);
system("pause");
}
阅读全文
0 0