您的位置:首页 > 编程语言 > C语言/C++

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

2017-07-20 02:04 537 查看
    点击打开链接       
#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");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: