题目描述
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
解答
AVL旋转:
向左旋 RR:左旋拎右 右的左儿子挂根
向右旋 LL:右旋拎左 左的右儿子挂根
LR:根节点的左儿子RR 再LL
RL:根节点的右儿子LL 再RR
思路:
构建平衡二叉树
弄明白插入的原理建树就很轻松了
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct AvlNode *Tree;
struct AvlNode{
int data;
Tree Lchild;
Tree Rchild;
int height;//记录结点的高度 方便旋转
};
int Max(int a,int b)
{
return (a>b?a:b);
}
int height(Tree T)
{
if(!T) return -1;