题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1066
考察AVL树的操作,大家从理论上都懂得过程,但实现起来。。。不知道怎么下手啊
/*
* 参考:http://biaobiaoqi.me/blog/2013/10/08/pat-1065-pat-1068/
*
* 考察AVL树的建立,调整操作,树的高度的更新。
* 需特别注意旋转操作、及如何确定何种操作。
*
*
*/
#include <stdio.h>
struct Node
{
Node *left;
Node *right;
int value;
int height;
// 构造
Node(int v)
{
value = v;
height = 0; // 叶节点层次为0
left = right = NULL; // 不可忘记指针初始化
}
};
int max(int x, int y) { return x > y ? x:y ; }
int get_height(Node *root)
{
return root == NULL ? -1 : root->height; // NULL所在层次为-1
}
Node * LL(Node *root)
{
Node * t = root->left;
root->left = t->right; //t的右孩子替代t,成为根节点的左孩子
t->right = root;
t->height = max(get_height(t->left), get_height(t->right)) + 1;
root->height = max(get_height(root->left), get_height(root->right)) + 1;
return t; //返回根节点t
}
Node *RR(Node *root)
{
Node * t = root->right;
root->right = t->left; //t的左孩子替代t,成为根节点的右孩子
t->left = root;
t->height = max(get_height(t->left), get_height(t->right)) + 1;
root->height = max(get_height(root->left), get_height(root->right)) + 1;
return t; //返回根节点t
}
Node *LR(Node *root)
{
// 先对左子树RR,再本身LL
root->left = RR( root->left );
return LL(root);
}
Node *RL(Node *root)
{
// 先右子树LL, 再左子树RR
root->right = LL( root->right);
return RR(root);
}
Node *insert(Node *root, int v)
{
if (root == NULL) {
root = new Node(v);
}
else
{
if(root->value > v)
{
// 插入左子树
root->left = insert(root->left, v);
// 调整
if ( (get_height(root->left) - get_height(root->right)) > 1)
{
if(get_height(root->left->left) > get_height(root->left->right))
{
// LL
root = LL(root);
}
else
{
// LR
root = LR(root);
}
}
}
else if(root->value < v)
{
// 插入到右子树
root->right = insert(root->right, v);
if( (get_height(root->right) - get_height(root->left)) > 1)
{
if( get_height(root->right->right) > get_height(root->right->left) )
{
// RR
root = RR(root);
}
else
{
root = RL(root);
}
}
} // else {}题目声明没有相同值的节点
}
// 更新高度,递归插入,在子树插入后,需要更新本节点高度
root->height = max(get_height(root->left), get_height(root->right)) + 1;
return root;
}
int main()
{
int n;
scanf("%d", &n);
Node *root=NULL; // 建立树根
while(n-- > 0)
{
int t;
scanf("%d", &t);
root = insert(root, t);
}
printf("%d\n", root->value);
return 0;
}