好久没写博客了,更新一波
这个是课本上的东西,一模一样,就是树的形式变换要记一下,没那个示意图估计是写不出来了
还有就是之前碰到二叉树建树的问题发现课本没有建二叉树的程序,其实就是这个题目,二叉树怎么都可以建出来,只是不一定是avl树(最坏是一条链)
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 21;
int n, a[maxn];
typedef struct Node * List;
struct Node {
int key;
List Right, Left;
};
List Newnode(int key)
{
List node = new Node;
node->key = key;
node->Right = node->Left = NULL;
return node;
}
int GetH(List root)
{
if (root == NULL)return 0;
else
{
int lh = GetH(root->Left);
int rh = GetH(root->Right);
return max(lh, rh) + 1;
}
}
List SingleRightR(List root)
{
List B = root->Right;
root->Right = B->Left;
B->Left = root;
return B;
}
List SingleLeftR(List root)
{
List B = root->Left;
root->Left = B->Right;
B->Right = root;
return B;
}
List DoubleRightLeftR(List A)
{
A->Right = SingleLeftR(A->Right);
return SingleRightR(A);
}
List DoubleLeftRightR(List A)
{
A->Left = SingleRightR(A->Left);
return SingleLeftR(A);
}
List Insert(List root, int key)
{
if (root == NULL)root = Newnode(key);
if (key > root->key)
{
root->Right = Insert(root->Right, key);
if (GetH(root->Right) - GetH(root->Left) == 2)
{
if (key > root->Right->key)root = SingleRightR(root);
else root = DoubleRightLeftR(root);
}
}
if (key < root->key)
{
root->Left = Insert(root->Left, key);
if (GetH(root->Left) - GetH(root->Right) == 2)
{
if (key < root->Left->key)root = SingleLeftR(root);
else root = DoubleLeftRightR(root);
}
}
return root;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)scanf("%d", &a[i]);
List root = NULL;
for (int i = 0; i<n; i++)
{
root = Insert(root, a[i]);
}
printf("%d\n", root->key);
return 0;
}