1. 程式人生 > 實用技巧 >歷時三年,Filecoin 主網正式上線 | 一週問答熱議

歷時三年,Filecoin 主網正式上線 | 一週問答熱議

1.AVL樹定義

  AVL 樹是一種平衡二叉樹,得名於其發明者的名字( Adelson-Velskii 以及 Landis)。(可見名字長的好處,命名都能多佔一個字母出來)。平衡二叉樹遞迴定義如下:

    a.左右子樹的高度差小於等於 1。

    b.其每一個子樹均為平衡二叉樹。

/*
        1.查詢
        2.插入
        3.建立 
*/
#include<cstdio>
#include<stdlib.h>
typedef int ElementType;
typedef struct node{
    int height;
    ElementType data;
    node
* lchild; node* rchild; }node,AVLTree; //生成一個新的結點 node* newNode(ElementType x){ node* p=(node*)malloc(sizeof(node)); if(p==NULL) return NULL; p->data=x; p->height=1; p->lchild=NULL; p->rchild=NULL; return p; } //返回以root為根節點的子樹的高度 int getHeight(node* root){
if(root==NULL) return 0; return root->height; } //計算root的平衡因子 int getBalanceFactor(node* root){ return getHeight(root->lchild)-getHeight(root->rchild); } int max(int a,int b){ if(a>b) return a; else return b; } //跟新以root為根節點的子樹的高度 void updateHeight(node* root){ root
->height=max(getHeight(root->lchild),getHeight(root->rchild))+1; } //查詢AVL樹中資料域為x的結點 node* search(node* root,ElementType x){ if(root==NULL) return NULL; if(root->data==x) return root; if(x>root->data) return search(root->rchild,x); else return search(root->lchild,x); } //左旋操作 void LeftRotation(node* &root){ node* temp=root->rchild; root->rchild=temp->lchild; temp->lchild=root; updateHeight(root); updateHeight(temp); root=temp; } //右旋操作 void RightRotation(node* &root){ node* temp=root->lchild; root->lchild=temp->rchild; temp->rchild=root; updateHeight(root); updateHeight(temp); root=temp; } //往AVL樹中插入一個數據域為x的新結點,並保持AVL樹特性 bool insert(node* &root,ElementType x){ node* p=newNode(x); if(p==NULL) return false; if(root==NULL){ root=p; return true; } if(x>root->data){ insert(root->rchild,x); updateHeight(root); if(getBalanceFactor(root)==-2){ if(getBalanceFactor(root->rchild)==-1){ LeftRotation(root); } else if(getBalanceFactor(root->rchild)==1){ RightRotation(root->rchild); LeftRotation(root); } } } else{ insert(root->lchild,x); updateHeight(root); if(getBalanceFactor(root)==2){ if(getBalanceFactor(root->lchild)==1){ RightRotation(root); } else if(getBalanceFactor(root->lchild)==-1){ LeftRotation(root->lchild); RightRotation(root); } } } } //建立AVL樹 node* Create(ElementType data[],int n){ node* root=NULL; for(int i=0;i<n;i++){ insert(root,data[i]); } return root; } int main(){ return 0; }