2022.1.23 练习 PAT甲 1020 Tree Traversals (原题链接)
题解如下:
#includeusing namespace std; const int MAX_SIZE=30; int post[MAX_SIZE];//后序 int in[MAX_SIZE];//中序 int n; struct node { int data; node* lchild; node* rchild; }; node* create(int posl,int posr,int inl,int inr) { if(posl>posr) return NULL; node* root=new node; root->data=post[posr]; int k; for(k=inl;k<=inr;k++) { if(in[k]==post[posr]) break; } int numleft=k-inl; root->lchild=create(posl,posl+numleft-1,inl,k-1); root->rchild=create(posl+numleft,posr-1,k+1,inr); return root; } void level(node* root) { int num=0; queue q; q.push(root); while(!q.empty()) { node* now=q.front(); q.pop(); cout< data; num++; if(num lchild!=NULL) q.push(now->lchild); if(now->rchild!=NULL) q.push(now->rchild); } } int main() { std::ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++) cin>>post[i]; for(int i=1;i<=n;i++) cin>>in[i]; node* root=create(1,n,1,n); level(root); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)