An AVL tree is a self-balancing binary search tree. In an AVL tree,
the heights of the two child subtrees of any node differ by at most
one; if at any time they differ by more than one, rebalancing is done
to restore this property. Figures 1-4 illustrate the rotation rules.
Now
given a sequence of insertions, you are supposed to tell the root of
the resulting AVL tree.
本题目要求是实现一棵平衡树并返回操作后该二叉平衡树的根节点。题面给出了四种在插入过程中旋转树的例子。所以很容易想到,在插入每个节点之后进行判断,若不平衡(左右节点的高度差为2),则判断其结构符合何种旋转特性,分类讨论后进入旋转的函数即可。只要细心地把每一个部分都实现就大功告成了。
代码如下
#include <iostream>
using namespace std;
struct Tree {
int val=0;
Tree* left=NULL;
Tree* right=NULL;
};
inline int max(int a, int b) { return a > b ? a : b; }
Tree* LLRotation(Tree* node)//见图
{
Tree* A = node;
Tree* B = node->left;
Tree* BR = B->right;
B->right = A;
A->left = BR;
return B;
};
Tree* LRRotation(Tree* node)//见图
{
Tree* A = node;
Tree* B = node->left;
Tree* BR = B->right;
Tree* C = B->right;
Tree* CL = C->left;
Tree* CR = C->right;
C->left = B;
C->right = A;
B->right = CL;
A->left = CR;
return C;
}
Tree* RRRotation(Tree* node)//见图
{
Tree* A = node;
Tree* B = node->right;
Tree* BL = B->left;
Tree* BR = B->right;
Tree* AR = A->right;
B->left = A;
A->right = BL;
B->right = BR;
return B;
}
Tree* RLRotation(Tree* node)//见图
{
Tree* A = node;
Tree* B = node->right;
Tree* BL = B->right;
Tree* AR = A->right;
Tree* C = B->left;
Tree* CL = C->left;
Tree* CR = C->right;
C->left = A;
C->right = B;
A->right = CL;
B->left = CR;
return C;
}
int getHeight(Tree* root)
{
if (!root)
return 1;
return 1 + max(getHeight(root->left), getHeight(root->right));
}
Tree* addTreeNode(Tree* root, int val)
{
if (!root)
{
Tree* newTree = new Tree;
newTree->val = val;
return newTree;
}
if (val > root->val)
{
root->right = addTreeNode(root->right,val);
if (getHeight(root->right) - getHeight(root->left) == 2)
{
if (root->right->val < val)
{
root = RRRotation(root);//祖祖孙孙都在右的话进RR
}
else
{
root = RLRotation(root);//爷爷的儿子在右、孙子在儿子的左边的话用RL
}
}
return root;
}
else if (val < root->val)
{
root->left = addTreeNode(root->left, val);
if (getHeight(root->left) - getHeight(root->right) == 2)
{
if (root->left->val > val)
{
root = LLRotation(root);//祖祖孙孙都靠左进LL
}
else
{
root = LRRotation(root);//爷爷的儿子在左,孙子在儿子的右边
}
}
return root;
}
}
int main()
{
int N;
cin >> N;
Tree* OriTree=new Tree;
OriTree = NULL;
for (int i = 0; i < N; i++)
{
int val;
cin >> val;
OriTree = addTreeNode(OriTree, val);
}
cout << OriTree->val << endl;
}