1123. Is It a Complete AVL Tree (30)

来源:互联网 发布:首份网络主播黑名单 编辑:程序博客网 时间:2024/04/30 14:04

1123. Is It a Complete AVL Tree (30)

#include <stdio.h>#include <malloc.h>struct AVLTNode{    struct AVLTNode *lchild,*rchild;    int key;    int height;}*T;int Max(int a,int b){    int k=(a>b?a:b);    return k;}int ComputeHeight(struct AVLTNode*T){    if(T)        return T->height;    return 0;}struct AVLTNode*leftRotation(struct AVLTNode *root){    struct AVLTNode *p=root->rchild;    root->rchild=p->lchild;    p->lchild=root;    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;    return p;}struct AVLTNode*rightRotation(struct AVLTNode *root){    struct AVLTNode *p=root->lchild;    root->lchild=p->rchild;    p->rchild=root;    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;    return p;}struct AVLTNode*rightleftRotation(struct AVLTNode *root){    root->rchild=rightRotation(root->rchild);    return leftRotation(root);}struct AVLTNode*leftrightRotation(struct AVLTNode *root){    root->lchild=leftRotation(root->lchild);    return rightRotation(root);}void Insertion(int curkey,struct AVLTNode **T){    if((*T)==NULL)    {        (*T)=(struct AVLTNode*)malloc(sizeof(struct AVLTNode));        (*T)->lchild=(*T)->rchild=NULL;        (*T)->key=curkey;        (*T)->height=0;    }    else if(curkey<((*T)->key))    {        Insertion(curkey,&(*T)->lchild);        if(ComputeHeight((*T)->lchild)-ComputeHeight((*T)->rchild)==2)        {            curkey<(*T)->lchild->key?((*T)=rightRotation(*T)):((*T)=leftrightRotation(*T));        }    }    else if(curkey>(*T)->key)    {        Insertion(curkey,&(*T)->rchild);        if(ComputeHeight((*T)->rchild)-ComputeHeight((*T)->lchild)==2)        {            curkey>(*T)->rchild->key?((*T)=leftRotation(*T)):((*T)=rightleftRotation(*T));        }    }    (*T)->height=Max(ComputeHeight((*T)->lchild),ComputeHeight((*T)->rchild))+1;}int isCompleteBtree(struct AVLTNode *T){    struct AVLTNode *queue[200],*s=T;    int front=0,rear=0;    queue[rear++]=T;    while((s=queue[front++])!=NULL)    {        queue[rear++]=s->lchild;        queue[rear++]=s->rchild;    }    while(front<rear)    {        s=queue[front++];        if(s!=NULL)            return 0;    }    return 1;}int main(){    int n,i;    T=NULL;    scanf("%d",&n);    for(i=0;i<n;++i)    {        int curkey;        scanf("%d",&curkey);        Insertion(curkey,&T);    }    int c=0;    struct AVLTNode *queue[200],*s=T;    int rear=0,front=0;    queue[rear++]=s;    while(front<rear)    {        s=queue[front++];++c;        printf("%d",s->key);        if(c!=n)printf(" ");        else printf("\n");        if(s->lchild)queue[rear++]=s->lchild;        if(s->rchild)queue[rear++]=s->rchild;    }    if(isCompleteBtree(T))printf("YES");    else printf("NO");    return 0;}
0 0
原创粉丝点击