#include<stdio.h>#include<stdlib.h>#include<queue>Usingnamespace Std;int post[32];Store post-post traversalint in[32];Storing the sequence traversalint n;Node countstruct node{int data; node* l; node* R;}; node* creat (int Postl,int Postr,int InL,int InR) {if (POSTL>POSTR)Indicates that the follow-up has been traversedReturnNULL; node* root= (node*) calloc (1,sizeof (node));or write node* root=new node; And calloc will automatically initialize root more conveniently root->data=post[postr]; Root->l=NULL; Root->r=NULL;int tmp=0;Mark Postr The position of this element under the middle sequence traversalfor (TMP=INL; tmp<=inr; ++tmp)if (In[tmp]==root->data)Breakint numleft=tmp-inl;"Thinking" in the post-traversal, the first numleft numbers are the next root of the left subtree Root->l=creat (Postl, postl+numleft-1, InL, tmp-1);"Caution" Here the subscript million attention!!! Root->r=creat (Postl+numleft, postr-1, tmp+1, InR);It's best to draw when you write this step.return root;return root Address}void BFS (node* root) {queue<node*> q;Create queue Q.push (root);int num=0;Record output count, control the number of spaceswhile (!q.empty ()) {++num; node* tmp=q.front (); Q.pop (); printf ("%d", Tmp->data);if (num<n) printf (" ");if (tmp->l!=NULL) Q.push (tmp->l);if (tmp->r!=NULL) Q.push (tmp->r); }}void DFS (node* root) {if (root==NULL)Return printf"%d", Root->data); DFS (ROOT->L); DFS (root->r);}int main () {scanf ( "%d", &n); for (int i=0; i<n; ++i) scanf ( "%d", &post[i]); for (int i=0; i<n; ++i) scanf ( "%d", &in[i]); node* root=creat (0,n-1,0,n- 1); //dfs (root);//sequence traversal, test build condition BFS (root); return 0;}
pat:1020. Tree traversals (+) AC