• 优先级队列的实现 和 层次遍历建树


    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    class priority_queue
    {
    private:
        vector<int> data;
    
    public:
        void push(int t){
            data.push_back(t);
            push_heap(data.begin(), data.end());
        }
    
        void pop(){
            pop_heap(data.begin(), data.end());
            data.pop_back();
        }
    
        int top() { return data.front(); }
        int size() { return data.size(); }
        bool empty() { return data.empty(); }
    };
    
    
    int main()
    {
        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

    层次遍历建树 

    按层建树是按照给定的数据数组来建立完全二叉树的过程。其中涉及到的基础知识有结构体的创建重命名以及使用、链表的创建和数组遍历。 
    #include <stdio.h>
    #include <stdlib.h>
    #define N 10
    #define MAX 100
    typedef struct node{
        int data;
        struct node *left;
        struct node *right;
    }BTnode;
    BTnode *deal(int a[],int n)
    {
        int i;
        BTnode *root;
        BTnode *queue[11];
        int front=0,rear=0;//按层,使用队列 
      for(i=0;i<n;i++){
        /*初始化新节点*/ 
      BTnode *t=(BTnode *)malloc(sizeof(BTnode));
      t->left=t->right=NULL;
      t->data=a[i];
       /*入队*/
       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++;
         }  
      }
      }
      return root;  
    }
    /*按层输出二叉树*/
    void PrintTree(BTnode *root)
    {
         BTnode *t=NULL;
         BTnode *queue[MAX];
         int front=0,rear=0;
         /*入队*/
         queue[++rear]=root;
         /*出队*/
         while(front!=rear){    
         t=queue[++front]; 
         printf("%d",t->data);
         if(t->left) queue[++rear]=t->left;
         if(t->right) queue[++rear]=t->right;
         }
    } 
    int main(void)
    {
        int a
    ={1,3,5,7,9,2,4,6,8,10};
        BTnode *root=NULL;
        root=deal(a,N);
        PrintTree(root);
        return 0;
    }
    View Code
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    PatentTips
    PatentTips
    PatentTips
    PatentTips
    PatentTips
    PatentTips
    PatentTips
    PatentTips
    How to build and run ARM Linux on QEMU from scratch
    How to debug Android Native Application with eclipse
  • 原文地址:https://www.cnblogs.com/chess/p/5312836.html
Copyright © 2020-2023  润新知