#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