【PAT】1123 Is It a Complete AVL Tree (30 分)

#include <iostream>
#include <math.h>
#include <queue>
using namespace std;

struct node
{
    int data;
    node* lchild,* rchild;
};

int getHeight(node* root){
    if(!root) return 0;
    int l=getHeight(root->lchild);
    int r=getHeight(root->rchild);
    return max(l,r)+1;
}

node* rightRotate(node* root){
    node* B=root->lchild;
    root->lchild=B->rchild;
    B->rchild=root;
    //如果每次新调用一次getHeight()函数,则不必更新树高~
    return B;
}
node* leftRotate(node* root){
    node* B=root->rchild;
    root->rchild=B->lchild;
    B->lchild=root;
    //如果每次新调用一次getHeight()函数,则不必更新树高~
    return B;
}

node* leftRightRotate(node* root){
    root->lchild=leftRotate(root->lchild);//把末端拆了,换个位置,再重接上去
    return rightRotate(root);//再换一次
}

node* rightLeftRotate(node* root){
    root->rchild=rightRotate(root->rchild);
    return leftRotate(root);
}

node* InsertT(node* root,int v){
    if(!root){
        root=new node;
        root->data=v;
        root->lchild=root->rchild=NULL;
        return root;
    }

    if(v<root->data){//左子树
        root->lchild=InsertT(root->lchild,v);
        if(getHeight(root->lchild)-getHeight(root->rchild)>=2){//左子树异常->右旋
            if(v<root->lchild->data){//左子树的左子树->RR
                root=rightRotate(root);
            }else{//左子树的右子树->LR
                root=leftRightRotate(root);
            }
        }
    }else{//右子树
        root->rchild=InsertT(root->rchild,v);
        if(getHeight(root->rchild)-getHeight(root->lchild)>=2){//右子树异常->左旋
            if(v>root->rchild->data){//右子树的右子树->LL
                root=leftRotate(root);
            }else{//右子树的左子树->RL
                root=rightLeftRotate(root);
            }
        }
    }
    return root;  
}

int flag=0;
int after=1,isComplete=1;
/*不是完全二叉树只有一种情况:左子树不存在,右子树存在
完全二叉树只可能用到结尾左子树存在,右子树不存在的一种判定*/
void levelTraversal(node* root){
    if(!root) return;
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node* tmp=q.front();
        q.pop();
        printf("%s%d",flag==1?" ":"",tmp->data);
        flag=1;
        if(tmp->lchild){
            if(after==0) isComplete=0;
            q.push(tmp->lchild);
        }else{
            after=0;
        }
        if(tmp->rchild){
            if(after==0) isComplete=0;
            q.push(tmp->rchild);
        }else{
            after=0;
        }
    }
}

int main(){
    int n;
    scanf("%d",&n);
    int a[n];
    node* root=NULL;
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
        root=InsertT(root,a[i]);
    }
    levelTraversal(root);
    printf("\n%s",isComplete?"YES":"NO");

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值