Implementation of priority queue and hierarchy traversal achievement

Source: Internet
Author: User

#include <iostream>#include<algorithm>#include<vector>using namespacestd;classpriority_queue{Private: Vector<int>data; Public:    voidPushintt)        {data.push_back (t);    Push_heap (Data.begin (), Data.end ()); }    voidpop () {pop_heap (Data.begin (), Data.end ());    Data.pop_back (); }    intTop () {returnData.front ();} intSize () {returndata.size ();} BOOLEmpty () {returndata.empty ();}};intMain () {priority_queue test; Test.push (3); Test.push (5); Test.push (2); Test.push (4);  while(!Test.empty ()) {cout<< test.top () <<Endl;    Test.pop (); }    return 0;}
View Code

Hierarchy Traversal Achievements

Building by layer is the process of establishing a complete binary tree according to a given array of data. The underlying knowledge involved is the creation and renaming of structs, as well as the use, creation and array traversal of linked lists.
#include <stdio.h>#include<stdlib.h>#defineN 10#defineMAX 100typedefstructnode{intdata; structNode *Left ; structNode *Right ;} Btnode; Btnode*deal (intA[],intN) {    inti; Btnode*Root; Btnode*queue[ One]; intFront=0, rear=0;//by layer, using queues   for(i=0; i<n;i++){    /*initializing a new node*/Btnode*t= (Btnode *)malloc(sizeof(Btnode)); T->left=t->right=NULL; T->data=A[i]; /*Queue*/queue[++rear]=T; if(i==0) {root=T; }Else{     if(!queue[rear/2]->Left ) {Queue[rear/2]->left=T; }Else{queue[rear/2]->right=T; Front++; }    }  }  returnRoot; }/*output binary tree by layer*/voidPrinttree (Btnode *root) {Btnode*t=NULL; Btnode*Queue[max]; intFront=0, rear=0; /*Queue*/queue[++rear]=Root; /*out Team*/      while(front!=rear) {T=queue[++Front]; printf ("%d",t->data); if(T->left) queue[++rear]=t->Left ; if(t->right) queue[++rear]=t->Right ; }} intMainvoid){    inta={1,3,5,7,9,2,4,6,8,Ten}; Btnode*root=NULL; Root=deal (A,n);    Printtree (root); return 0;}
View Code

Implementation of priority queue and hierarchy traversal achievement

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: info-contact@alibabacloud.com 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.