pat:1020. Tree traversals AC

Source: Internet
Author: User

#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&GT;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-&GT;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.