#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;}
新闻热点
疑难解答