码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1020. Tree Traversals

时间:2016-03-02 00:09:48      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

//典型后中省树,这种方法必须有 中序序列来确定根的位置,然后二分建树;

//因为用的vc,之前用序列位置建树通不过,用坐标建树通过了,怀疑vc的功能限制,有时间再来测试,眼下感觉还是坐标好啊,用地址巧了半个晚上了找不着八哥,还不A,哭晕

#include<cstdio>
//#include<cstring>
#include<queue>
#include<vector>
//#include<algorithm>
using namespace std;
const int maxn=31;
struct node
{
int data;
node *lchild,*rchild;
};
int pre[maxn],post[maxn],in[maxn];
int n;
queue<node*>q;
vector<int>level;
node *create(int postl,int postr,int inl,int inr)
{
if(postl>postr)return NULL;
node* root=new node;
root->data=post[postr];
root->lchild=root->rchild=NULL;
int k;
for(k=inl;k<=inr;k++)
if(in[k]==post[postr])break;
int numleft=k-inl;
root->lchild=create(postl,postl+numleft-1,inl,k-1);
root->rchild=create(postl+numleft,postr-1,k+1,inr);
return root;
}
void bfs(node *root)
{
if(root!=NULL)q.push(root);
while(!q.empty())
{
node *tmp=q.front();q.pop();
level.push_back(tmp->data);
if(tmp->lchild!=NULL)q.push(tmp->lchild);
if(tmp->rchild!=NULL)q.push(tmp->rchild);
}
}
int main()
{
freopen("input.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
int i;
for( i=0;i<n;i++)scanf("%d",&post[i]);
for( i=0;i<n;i++)scanf("%d",&in[i]);
node *root=create(0,n-1,0,n-1);
bfs(root);
for( i=0;i<level.size();i++)
{
if(i==level.size()-1)printf("%d\n",level[i]);
else printf("%d ",level[i]);
}
}
return 0;
}

PAT1020. Tree Traversals

标签:

原文地址:http://www.cnblogs.com/zeroArn/p/5233257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!