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

来源:互联网 发布:android源码编译后rom 编辑:程序博客网 时间:2024/06/11 12:45
点击打开pat链接#include<iostream>
#include<math.h>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<string>
#include<vector>
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);
  }
 else if(getbalancefactor(root->rchild)==-1)
  { L(root);
  }
  }
 }
}
int main(){
 int num;
 cin>>num;
 node *root;
 int qw;
 for(int i=0;i<num;i++)
 {
  cin>>qw;
  insert(root,qw);
 }
 cout<<root->num;
 return 0;
}
阅读全文
0 0
原创粉丝点击