设为首页 加入收藏

TOP

PAT程序设计考题——甲级1066(Root of AVL Tree ) C++实现
2017-07-07 10:22:38 】 浏览:713
Tags:PAT 程序设计 考题 甲级 1066 Root AVL Tree 实现

PAT程序设计考题——甲级1066(Root of AVL Tree ) C++实现。

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define INF 100000000
#define maxn 100010


struct node{
int num,height;
node *lchild,*rchild;
};
node* newnode(int v)
{ node *root;
root=new node;
root->num=v;
root->height=1;
root->lchild=root->rchild=NULL;
return root;
}
int getheight(node *root)
{ if(root==NULL) return 0;
return root->height;
}
int getbalancefactor(node *root )
{
return getheight(root->lchild)-getheight(root->rchild);
}
void updateheight(node* root)
{
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
}
void L(node *&root){
node *temp;
temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void R(node *&root)
{
node *temp;
temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateheight(root);
updateheight(temp);
root=temp;

}
void insert(node* &root,int v)
{
if(root==NULL) {
root=newnode(v);
return;}
if(root->num>v)
{
insert(root->lchild,v);
updateheight(root);
if(getbalancefactor(root)==2)
{ if(getbalancefactor(root->lchild)==1)
{ R(root);
}
else if(getbalancefactor(root->lchild)==-1)
{ L(root->lchild);
R(root);
}}}
else{
insert(root->rchild,v);
updateheight(root);
if(getbalancefactor(root)==-2){
if(getbalancefactor(root->rchild)==1)
{
R(root->rchild);
L(root);
}
elseif(getbalancefactor(root->rchild)==-1)
{ L(root);
}
}
}
}
int main(){
int num;
cin>>num;
node *root;
int qw;
for(int i=0;i {
cin>>qw;
insert(root,qw);
}
cout< num;
return 0;
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇c++学习笔记-----函数指针 下一篇c++学习笔记----指针函数

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目