栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

AVL树的插入+层次遍历+判断是否为完全二叉树板子

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AVL树的插入+层次遍历+判断是否为完全二叉树板子

#include
using namespace std;

const int N=100;
int l[N],r[N],v[N],h[N],idx;
int pos[N];
int p[N];
queue q;
int root=0;
int n;
int update(int u){//更新深度
    h[u]=max(h[l[u]],h[r[u]])+1;
}

int R(int &u){//右旋
    int p=l[u];
    l[u]=r[p];
    r[p]=u;
    update(u),update(p);
    u=p;
}

int L(int &u){//左旋
    int p=r[u];
    r[u]=l[p];
    l[p]=u;
    update(u),update(p);
    u=p;
}

int get_balance(int u){//获取左子树-右子树高度差
    return h[l[u]]-h[r[u]];
}

void insert(int &u,int w){//在u节点处插入值为w的结点
    if(!u){
        u=++idx;
        v[u]=w;
    }else if(w
        //左
        insert(l[u],w);
        if(get_balance(u)==2){
            if(get_balance(l[u])==1){
                //右旋
                R(u);
            }else{
                L(l[u]);
                R(u);
            }
        }
    }else{
        //右
        insert(r[u],w);
        if(get_balance(u)==-2){
            if(get_balance(r[u])==-1){
                //左旋
                L(u);
            }else{
                R(r[u]);
                L(u);
            }
        }
    }
    update(u);
}

bool bfs(int root){//层次遍历 同时通过pos判断是否为完全二叉树
    pos[root]=1;
    q.push(root);
    int num=0;
    bool res=true;
    while(q.size()){
        int t=q.front();
        p[num++]=t;
        if(pos[t]>n)res=false;
        if(l[t]){
            pos[l[t]]=pos[t]*2;
            q.push(l[t]);
        }
        if(r[t]){
            pos[r[t]]=pos[t]*2+1;
            q.push(r[t]);
        }
        q.pop();
    }
    
    return res;
}

int main(){
    cin>>n;
    for(int i=0;i
        int w;
        cin>>w;
        insert(root,w);
    }
    
    int res=bfs(root);
    cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022228.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号