# sdut oj3374 数据结构实验之查找二：平衡二叉树

## 示例输入

```5
88 70 61 96 120```

`70`

## 提示

``````#include <bits/stdc++.h>
using namespace std;

typedef int element;

struct Tree
{
element data;
int deep;
Tree *lchild,*rchild;
};

int Max(int a,int b)
{
return a>b ? a:b;
}

int Deep(Tree *T)
{
if(!T)
return -1;
else
return T->deep;
}

Tree *LL(Tree *T)///右旋
{
Tree *p = T->lchild;
T->lchild = p->rchild;
p->rchild = T;
p->deep = Max(Deep(p->lchild),Deep(p->rchild))+1;
T->deep = Max(Deep(T->lchild),Deep(T->rchild))+1;
return p;
}

Tree *RR(Tree *T)///左旋
{
Tree *p = T->rchild;
T->rchild = p->lchild;
p->lchild = T;
p->deep = Max(Deep(p->lchild),Deep(p->rchild))+1;
T->deep = Max(Deep(T->lchild),Deep(T->rchild))+1;
return p;
}

Tree *LR(Tree *T)///先左旋后右旋
{
T->lchild = RR(T->lchild);
return LL(T);
}

Tree *RL(Tree *T)///先右旋后左旋
{
T->rchild = LL(T->rchild);
return RR(T);
}

Tree *Creat(Tree *T,int n)
{
if(!T)
{
T = new Tree;
T->data = n;
T->deep = 0;
T->lchild = T->rchild = NULL;
}
else
{
if(n < T->data)
{
T->lchild = Creat(T->lchild,n);
if(Deep(T->lchild)-Deep(T->rchild) > 1)
{
if(T->lchild->data > n)
T = LL(T);
else
T = LR(T);
}
}
else if(n > T->data)
{
T->rchild = Creat(T->rchild,n);
if(Deep(T->rchild)-Deep(T->lchild) > 1)
{
if(T->rchild->data < n)
T = RR(T);
else
T = RL(T);
}
}
}
T->deep = Max(Deep(T->lchild),Deep(T->rchild)) + 1;
return T;
}

int main()
{
int n,m;
Tree *T = NULL;
scanf("%d",&n);
for(int i = 0;i < n;i++)
{
scanf("%d",&m);
T = Creat(T,m);
}
printf("%d\n",T->data);
return 0;
}
``````

原文作者：平衡二叉树
原文地址: https://blog.csdn.net/Annfan123/article/details/52201273
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。