1066 Root of AVL Tree(25 分)
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.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120
Sample Output 1:
70
Sample Input 2:
7
88 70 61 96 120 90 65
Sample Output 2:
88
命名方式是:插入该节点导致哪个节点不平衡 就是这个节点的哪边的哪边
比如figure3发生问题是插入90 导致70这个节点不平衡 所以我们称他为右左双旋
代码怎么写 。。。。右左双旋 就近原则先解决最近的哪个 虽然右节点平衡 但是我们还是先解决右边的这个解决
所以去调用 左旋 其次 解决根节点 。。。。。具体就这样子
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
int getHeight(struct node* tree)
{
if(tree == NULL)
return 0;
int l = getHeight(tree->left);
int r = getHeight(tree->right);
return max(l, r) + 1;
}
struct node* rightRotate(struct node*tree)
{
struct node*temp = tree->right;
tree->right = temp -> left;
temp->left = tree;
return temp;
}
struct node* leftRotate(struct node *tree)
{
struct node*temp = tree->left;
tree->left = temp->right;
temp->right = tree;
return temp;
}
struct node* leftrightRotate(struct node* tree)
{
tree->left = rightRotate(tree->left);
return leftRotate(tree);
}
struct node* rightleftRotate(struct node* tree)
{
tree->right = leftRotate(tree->right);
return rightRotate(tree);
}
struct node* insert(struct node* tree, int val)
{
if(tree == NULL)
{
tree = new node();
tree->data = val;
tree->left = tree->right = NULL;
return tree;
}
if(val < tree->data)
{
tree->left = insert(tree->left,val);
int l = getHeight(tree->left);
int r = getHeight(tree->right);
if(l - r >= 2)
{
if (val < tree->left->data)
tree = leftRotate(tree);//发生问题在左子树的左边
else
tree = leftrightRotate(tree); //发生问题在左子树的右边
}
}else
{
tree->right = insert(tree->right,val);
int l = getHeight(tree->left);
int r = getHeight(tree->right);
if(r - l >= 2)
{
if(val > tree->right->data)
tree = rightRotate(tree);//发生问题在右子树的右边
else
tree = rightleftRotate(tree); //发生问题在右子树的左边
}
}
return tree;
}
int main()
{
int n,x;
scanf("%d",&n);
struct node* tree = NULL;
for(int i = 1; i <= n; i++)
{
scanf("%d",&x);
tree = insert(tree,x);
}
printf("%d\n",tree->data);
}