您的位置:首页 > 其它

那些年我们一起考过的浙大

2017-03-03 09:05 246 查看
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>

using namespace std;

const int maxn=100;
int in[maxn];
vector<int> le;

struct Node
{
int data;
Node* lchild;
Node* rchild;
};
int k;
Node* create(vector<int> layer,int inL,int inR)
{
if(layer.size()==0)
return NULL;
Node* root=new Node;
root->lchild=root->rchild=NULL;
root->data=layer.front();

vector<int> layerleft;
vector<int> layerright;

for(int i=inL;i<=inR;i++)
{
if(in[i]==layer.front())
{
k=i;
break;
}
}

bool isleft=false;
for(int i=1;i<layer.size();i++)
{
for(int j=inL;j<k;j++)
{
if(layer[i]==in[j])
{
isleft=true;
}
}
if(isleft)
{
layerleft.push_back(layer[i]);
isleft=false;
}
else
{
layerright.push_back(layer[i]);
}
}
root->lchild=create(layerleft,inL,k-1);
root->rchild=create(layerright,k+1,inR);
return root;
}
int num;
int maxdepth=0;
int maxright=0;
int minleft=0;
int minright=0;
void preorder(Node* root,int n,int depth,int right,int m)
{
if(root==NULL)
return;
printf("%d",root->data);
num++;
if(num<n) printf(" ");
if(num==n) printf("\n");
if(depth>maxdepth) maxdepth=depth;
if(right>maxright) maxright=right;
if(m>minright) minright=m;
if(m<minleft) minleft=m;
preorder(root->lchild,n,depth+1,right,m-1);
preorder(root->rchild,n,depth+1,right+1,m+1);
}

void postorder(Node* root,int n)
{
if(root==NULL)
return;
postorder(root->lchild,n);
postorder(root->rchild,n);
printf("%d",root->data);
num++;
if(num<n) printf(" ");
}
int main()
{
int n;
scanf("%d",&n);
int temp;
for(int i=0;i<n;i++)
{
scanf("%d",&temp);
le.push_back(temp);
}
for(int i=0;i<n;i++)
{
scanf("%d",&in[i]);
}

Node* root=create(le,0,n-1);
num=0;
preorder(root,n,1,1,0);

num=0;
postorder(root,n);
printf("\n");
printf("%d\n",maxdepth);
printf("%d\n",maxright);
printf("%d",minright-minleft+1);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: