// VSPAT.cpp : 定义控制台应用程序的入口点。
//
#include<cmath>
#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<stack>
#include<vector>
#include<queue>
#include<string>
#include<map>
using namespace std;
//70min
//耗时于思考和改bug
/*************************
题意:给出前序和后序,求中序
若中序不唯一,输出任意一个,并输出No
*************************/
/************************
求解要点:
对于一棵树
前序序列的首位和后序序列的末位一定相同,且为根
前序根后的那位一定为“左”子树根。
后序根前的那位一定为“右”子树。
前: 根 左子树根 XXXXXXX
后: XXXXXXX 右子树根 根
然后在后序序列中找到左子树根,左子树根的右边都是左子树
前: 根 [左子树根 XXX][右子树根XXX]
后: [XXX左子树根] [XXX右子根] 根
根据如此划分进行递归
★若左树根=右树根,则仅1个子树,故极可能是左也可能是右
这里同意划分为左根,右孩子=-1
************************/
/***********************
笔记:
注意输入中,树的数字可能不为1~N,可能为很大的整数。
故用数组做树结构时要留意大小。
*********************/
#define M 1000
int pre[M],post[M];
int Left[M],Right[M];
int flag = 1,n;
int buildtree(int node,int prel,int prer,int postl,int postr)
{
int i,lchild,rchild;
if(prel==prer||prer>=n||prel<0||postl<0||postr>=n)
{
Left[node]=-1;
Right[node]=-1;
return node;
}
//printf("nownode=%d\n",node);
lchild=pre[prel+1];
rchild=post[postr-1];
if(lchild==rchild)
{
flag=0;
Left[node]=buildtree(lchild,prel+1,prer,postl,postr-1);
Right[node]=-1;
//printf("node=%d,left=%d,right=%d\n",node,Left[node],Right[node]);
return node;
}
for(i=postr-1;i>=postl;i--)
if(post[i]==lchild)
break;
//左子树为 前序左到中, 后序左到中
//右子树为 前序中到右 后序中到右
Left[node]=buildtree(lchild,prel+1,prel+1+i-postl,postl,i);
Right[node]=buildtree(rchild,prel+i-postl+2,prer,i+1,postr-1);
return node;
}
int k=0;
void orderprint(int node)
{
if(node<=0)
return ;
orderprint(Left[node]);
printf("%d",node);
k++;
if(k<n)
cout<<" ";
else cout<<endl;
orderprint(Right[node]);
}
int main()
{
int i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&pre[i]);
for(i=0;i<n;i++)
scanf("%d",&post[i]);
int root=pre[0];
buildtree(root,0,n-1,0,n-1);
if(flag==1)
cout<<"Yes"<<endl;
else cout<<"No"<<endl;
orderprint(root);
return 0;
}
PAT 1119. Pre- and Post-order Traversals (30) 用前序、后序求中序
最新推荐文章于 2021-01-13 00:47:29 发布