#include <iostream>
using namespace std;
//AVL树节点信息
struct TreeNode
{
int data;
int height;
//无符号频率(数据出现的次数)
unsigned int freq;
TreeNode* lchild;
TreeNode* rchild;
};
int max(int x,int y)
{
return x>y? x:y;
}
int getHeight(TreeNode* node)
{
if(node)
return node->height;
return -1;
}
TreeNode* rotateLeft(TreeNode* A)
{
//LL
//A为根节点,B为它的左孩子
//A的左子树变为B的右子树
//B的右子树变为A
//B为根
TreeNode* B = A->lchild;
A->lchild = B->rchild;
B->rchild = A;
return B;
}
TreeNode* rotateRight(TreeNode* &A)
{
//RR
//A为根节点,B为A的右孩子
//A的右子树为B的左子树
//B的左子树为A
//B为根
TreeNode* B = A->rchild;
A->rchild = B->lchild;
B->lchild = A;
return B;
}
TreeNode* rotateLR(TreeNode* A)
{
A->lchild = rotateRight(A->lchild);
return rotateLeft(A);
}
TreeNode* rotateRL(TreeNode* A)
{
A->rchild = rotateLeft(A->rchild);
return rotateRight(A);
}
void insert(TreeNode* &node,TreeNode* s)
{
if(!node)
{
node = s;
}
else if(s->data < node->data)
{
insert(node->lchild,s);
if(2 == getHeight(node->lchild) - getHeight(node->rchild)){
if(s->data < node->lchild->data)
node = rotateLeft(node); //执行旋转之后,将为返回的根节点赋予当前节点node,方便node的父节点连接
else
node = rotateLR(node);
}
}
else if(s->data > node->data)
{
insert(node->rchild,s);
if(2 == getHeight(node->rchild) - getHeight(node->lchild)){
if(s->data > node->rchild->data)
node = rotateRight(node);
else
node = rotateRL(node);
}
}
else
node->freq++;
node->height = max(getHeight(node->lchild) , getHeight(node->rchild)) + 1;
}
void order(TreeNode* root)
{
if(root){
order(root->lchild);
cout << root->data << " ";
order(root->rchild);
}
}
void pre(TreeNode* root)
{
if(root){
cout << root->data << " ";
pre(root->lchild);
pre(root->rchild);
}
}
TreeNode* find(int k,TreeNode* root)
{
if(root == NULL)
return NULL;
if(k < root->data)
return find(k, root->lchild);
else if(k > root->data)
return find(k,root->rchild);
else
return root;
}
int main()
{
const n = 7;
int r[n] = {20,35,40,15,30,25,38};
TreeNode* root = NULL;
for (int i = 0; i < n; ++i)
{
TreeNode* s = new TreeNode;
s->data = r[i];
s->freq = 1;
s->height = 0;
s->lchild = NULL;
s->rchild = NULL;
insert(root,s);
}
cout << "order: ";order(root);
cout << endl;
cout << "pre: "; pre(root);
cout << endl;
cout << "root:" << root->data << endl;
//cout << find(20,root)->data << endl;
return 0;
}