# 平衡二叉树

## 题目描述

Problem Description

Input

Output

Sample Input

5
88 70 61 96 120
Sample Output

70

## 代码 & 分析

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node{
int data;
int depth;
struct node * left;
struct node * right;
};
typedef struct node * tree;

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

int deep(tree t){
if(t==NULL)
return -1;
else{
return t->depth;
}
}
tree LL(tree &t){                            // LL情况  进行向右的顺时针旋转
tree p;
p=t->left;
t->left = p->right;
p->right = t;
p->depth = maxx(deep(p->left), t->depth) + 1;
t->depth = maxx(deep(t->left), deep(t->right)) + 1;
return p;
}
tree RR(tree &t){                          //RR情况   其实很好记的 很对称  向左逆时针旋转
tree p;
p= t->right;
t->right = p->left;
p->left = t;
p->depth = maxx(deep(p->right), t->depth) + 1;
t->depth = maxx(deep(t->left), deep(t->right)) + 1;
return p;
}

tree RL(tree &t){                          //搞定前两个基础的情况 直接交给递归 因为剩下的是复合旋转  RL 就是先RR后LL
t->right = LL(t->right);
return RR(t);
}
tree LR(tree &t){              //反之
t->left = RR(t->left);
return LL(t);
}

tree create(tree &t, int x){            //在二叉排序树的基础上稍作改变
if(t==NULL){
t = new node;
t->left = NULL;
t->right = NULL;
t->data = x;
t->depth = 0;
}
else if(x < t->data){
t->left = create(t->left, x);
if(deep(t->left) - deep(t->right) > 1){     //增加的部分就是判断某个点不符合性质则进行改变
if(x < t->left->data)
t=LL(t);
else
t=LR(t);
}
}
else if(x > t->data){
t->right = create(t->right, x);
if(deep(t->right) - deep(t->left) > 1){
if(x > t->right->data)
t = RR(t);
else
t = RL(t);
}
}
t->depth = maxx(deep(t->left), deep(t->right)) + 1;              //最后更新这个树节点的深度
return t;
}

int main(){
int n,i,x;
cin>>n;
tree t = NULL;
for(int i=0; i<n; i++){
cin>>x;
t = create(t, x);
}
cout<<t->data<<endl;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120