1066. Root of AVL Tree (25)

来源:互联网 发布:淘宝服装店铺简介范文 编辑:程序博客网 时间:2024/06/05 19:29
#include<cstdio>#include<algorithm>using namespace std;#define maxn 30struct node{  int v,heigth;  node *lchild,*rchild;};int data[maxn]={0},n;node* newN(int x){  node* now = new node;  now->v = x;  now->heigth = 1;  now->lchild = now->rchild = NULL;  return now;}int getHeight(node* root){  if(root == NULL)    return 0;  return root->heigth;}int getBF(node* root){  return getHeight(root->lchild) - getHeight(root->rchild);}void updateHeigth(node* root){  root->heigth = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;}//右旋Rvoid R(node* &root){  //获取左孩子  node* lchild = root->lchild;  //root的左孩子变为lchild的右孩子  root->lchild = lchild->rchild;  //root变为lchild的右孩子  lchild->rchild = root;  //更新root和孩子的高度  updateHeigth(root);  updateHeigth(lchild);  //吧孩子变为根节点  root = lchild;}//左旋Lvoid L(node* &root){  //获取左孩子  node* rchild = root->rchild;  //root的左孩子变为lchild的右孩子  root->rchild = rchild->lchild;  //root变为lchild的右孩子  rchild->lchild = root;  //更新root和孩子的高度  updateHeigth(root);  updateHeigth(rchild);  //吧孩子变为根节点  root = rchild;}void insert(node* &root,int x){  //空,这里插入  if(root == NULL)  {    root = newN(x);    return;  }  //小于根,左边  if(x < root->v)  {    //递归插入    insert(root->lchild,x);    //更新高度    updateHeigth(root);    //获取平衡因子    if(getBF(root) == 2)    {      //2 1直接R      if(getBF(root->lchild) == 1)      {        R(root);      }      else if(getBF(root->lchild) == -1)      {        //先L,lchild,在R        L(root->lchild);        R(root);      }    }  }  //大于根,右边  else  {    //递归插入    insert(root->rchild,x);    //更新高度    updateHeigth(root);    //获取平衡因子    if(getBF(root) == -2)    {      //2 1直接R      if(getBF(root->rchild) == -1)      {        L(root);      }      else if(getBF(root->rchild) == 1)      {        //先L,lchild,在R        R(root->rchild);        L(root);      }    }  }}node* creat(int data[], int n){  node* root = NULL;  for(int i=0 ;i<n; i++)  {    insert(root, data[i]);  }  return root;}int main(){  node* root;  scanf("%d",&n);  for(int i=0; i<n; i++)    scanf("%d",&data[i]);  root = creat(data, n);  printf("%d",root->v);  return 0;}

0 0
原创粉丝点击