前面刷了,但是太久都忘记了要注意的点了。等以后有时间再补了。
平衡二叉树 = = 真的是转来转去的。。注意下LL RR LR RL是怎么定义的。LL是调皮的节点在平衡因子为2的节点的左孩子的左孩子上。就好理解了。
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{
int data;
Node * l;
Node * r;
int h;
Node() { l = NULL; r = NULL; h = -1; }
};
typedef Node * Tree;
Tree tree = NULL;
int n;
int GetHeight(Tree t) {
if (t) {
return t->h;
}
return -1;
}
Tree LL(Node * t) {
Node * temp = t->l;
t->l = temp->r;
temp->r = t;
temp->h = max(GetHeight(temp->l), GetHeight(temp->r)) + 1;
t->h = max(GetHeight(t->l), GetHeight(t->r)) + 1;
return temp;
}
Tree RR(Node * t) {
Node * temp = t->r;
t->r = temp->l;
temp->l = t;
temp->h = max(GetHeight(temp->l), GetHeight(temp->r)) + 1;
t->h = max(GetHeight(t->l), GetHeight(t->r)) + 1;
return temp;
}
Tree RL(Node * t) {
t->r = LL(t->r);
return RR(t);
}
Tree LR(Node * t) {
t->l = RR(t->l);
return LL(t);
}
Node * Insert(int num ,Tree t) {
if (!t) { //NULL 新建节点
t = new Node;
t->data = num;
t->h = 0;
}
else if (num < t->data) { //左子树
t->l = Insert(num, t->l);
if (GetHeight(t->l) - GetHeight(t->r) == 2) {//要调整
if (num < t->l->data) {//LL
t = LL(t);
}
else//LR
t = LR(t);
}
}
else if (num > t->data) { //右子树
t->r = Insert(num, t->r);
if (GetHeight(t->r) - GetHeight(t->l) == 2) {//要调整
if (num > t->r->data) {
t = RR(t);
}
else
t = RL(t);
}
}
t->h = max(GetHeight(t->l), GetHeight(t->r)) + 1;
return t;
}
int main() {
cin >> n;
int temp;
for (int i = 0; i < n; i++) {
cin >> temp;
tree = Insert(temp, tree);
}
cout << tree->data << endl;
return 0;
}