AVL-平衡二叉树的创建和遍历

在此,主要介绍,AVL的创建,仅仅用层次遍历验证AVL树创建的正确性,想要详细了解,先序,中序,后序和层次遍历,请参考我之前的发布的一篇介绍遍历的博客---- https://blog.csdn.net/kz_java/article/details/88358491 建树->先序-中序-后序-层次遍历

#include<stdio.h>
#include<queue>
using namespace std;
//AVL 19-3-10
int i,N,num[10005];
struct node{
    int data,height;
    node* lchild,*rchild;
};
node* newNode(int x){
    node* Node=new node;
    Node->data=x;
    Node->height=1;
    Node->lchild=Node->rchild=NULL;
    return Node;
}
int getHeight(node*root){
    if(root==NULL)
        return 0;
    return root->height;
}
int getBF(node*root){
    return getHeight(root->lchild)-getHeight(root->rchild);
}
void updataHeight(node*root){
    root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
void R(node*&root){
    node*temp=root->lchild;
    root->lchild=temp->rchild;
    temp->rchild=root;
    updataHeight(root);
    updataHeight(temp);
    root=temp;
}
void L(node*&root){
    node*temp=root->rchild;
    root->rchild=temp->lchild;
    temp->lchild=root;
    updataHeight(root);
    updataHeight(temp);
    root=temp;
}
void insert(node*&root,int x){
    if(root==NULL){
        root=newNode(x);
        return;
    }
    if(x<root->data){
        insert(root->lchild,x);
        updataHeight(root);
        if(getBF(root)==2){
            if(getBF(root->lchild)==1){
                R(root);
            }else if(getBF(root->lchild)==-1){
                L(root->lchild);
                R(root);
            }
        }
    }else{
        insert(root->rchild,x);
        updataHeight(root);
        if(getBF(root)==2){
            if(getBF(root->lchild)==1){
                L(root);
            }else if(getBF(root->rchild)==-1){
                R(root->rchild);
                L(root);
            }
        }
    }
}
node* Create(int data[],int len){
    node*root=NULL;
    for(int i=0;i<len;i++)
        insert(root,data[i]);
    return root;
}
void LayerOrder(node*root){
    queue<node*>q;
    q.push(root);
    while(!q.empty()){
        node*now=q.front();
        q.pop();
        printf("%d ",now->data);
        if(now->lchild)
            q.push(now->lchild);
        if(now->rchild)
            q.push(now->rchild);
    }
}
int main(){
    scanf("%d",&N);
    for(i=0;i<N;i++)
        scanf("%d",num+i);
    node*root=Create(num,N);
    LayerOrder(root);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值