平衡二叉树模板

来源:互联网 发布:编程要学多久 编辑:程序博客网 时间:2024/05/14 14:06
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct node{    int ndata;             //记录关键字数值    node *l,*r;    int nheight;           //平衡因子};int height(node* p)        //返回树p的深度{    if(p==NULL)    return -1;    return p->nheight;}node* LLRotate(node* p)     //对LL型直接在不平衡结点进行左旋转{    node* p1;    p1=p->l;    p->l=p1->r;    p1->r=p;    p->nheight=max(height(p->l),height(p->r))+1;  //结点的位置变了,要更新结点的高度值    p1->nheight=max(height(p1->l),p->nheight)+1;    return p1;}node* RRRotate(node* p)   //对RR型直接在不平衡结点进行右旋转{    node* p1;    p1=p->r;    p->r=p1->l;    p1->l=p;    p->nheight=max(height(p->l),height(p->r))+1;    p1->nheight=max(height(p1->r),p->nheight)+1;    return p1;}node* LRRotate(node* p){    p->l=RRRotate(p->l);   //在不平衡结点p的左儿子处进行右旋转    return LLRotate(p);    //在不平衡结点p处进行左旋转并返回新的根}node* RLRotate(node* p){    p->r=LLRotate(p->r);   //在不平衡结点p的右儿子处进行左旋转    return RRRotate(p);    //在不平衡结点p处进行左旋转并返回新的根}node* _Insert(int s,node* p){    if(p==NULL)            //待插入的值赋给新开辟的结点    {        p=new node;        p->ndata=s;        p->nheight=0;        p->l=p->r=NULL;    }    else if(s<p->ndata)    //若待插入的值小于p的关键字数值,则插入到左子树中    {        p->l=_Insert(s,p->l);        if(height(p->l)-height(p->r)==2)   //该树出现不平衡        {            if(s<p->l->ndata)      //若待插入的值插到了左儿子的左子树上则单旋转                p=LLRotate(p);            else                   //反之,双旋转                p=LRRotate(p);        }    }    else if(s>p->ndata)     //道理同上    {        p->r=_Insert(s,p->r);        if(height(p->l)-height(p->r)==-2)        {            if(s>p->r->ndata)                p=RRRotate(p);            else                p=RLRotate(p);        }    }    p->nheight=max(height(p->l),height(p->r))+1;    return p;}int main(){    int n;    while(~scanf("%d",&n))    {        node *head=NULL;        while(n--)        {            int x;            scanf("%d",&x);            head=_Insert(x,head);        }        printf("%d\n",head->ndata);    }    return 0;}

0 0