/*
平衡二叉树 AVL
AVL树的原理是左右高度差不大于1
*/
#include <iostream>
using namespace std;
typedef struct node{
char value;
struct node *left,*right,*father;
}AVL;
void Create(AVL* &root)
{
root = new AVL;
root->value = 'X'; root->father = NULL; root ->right = NULL;
AVL* avl_node = NULL;
avl_node = new AVL;
avl_node->value = 'A'; root->left = avl_node; avl_node->father = root;
avl_node = new AVL;
avl_node->value = 'B'; root->left->left = avl_node; avl_node->father = root->left;
avl_node = new AVL;
avl_node->value = 'C'; root->left->right = avl_node; avl_node->father = root->left; avl_node->left = NULL; avl_node->right = NULL;
avl_node = new AVL;
avl_node->value = 'D'; root->left->left->left = avl_node; avl_node->father = root->left->left; avl_node->right = NULL;
avl_node = new AVL;
avl_node->value = 'E'; root->left->left->right = avl_node; avl_node->father = root->left->left; avl_node->left = NULL; avl_node->right = NULL;
avl_node = new AVL;
avl_node->value = 'F'; root->left->left->left->left = avl_node; avl_node->father = root->left->left->left; avl_node->left = NULL; avl_node->right = NULL;
}
void RightRemote(AVL* &root) /*右旋*/
{
if(root == NULL) return ;
AVL* pMark = NULL, *pNode = NULL;
pMark = root->left; pNode = pMark->left;
/*处理三个孩子关系*/
pMark->left = pNode->right;
pNode->right = pMark;
if(pMark->father){
if(pMark == pMark->father->left){
pMark->father->left = pNode;
}
else{
pMark->father->right = pNode;
}
}
else{
root = pNode;
}
/*处理三个父亲关系*/
if(pMark->left)
pMark->left->father = pMark;
pNode->father = pMark->father;
pMark->father = pNode;
}
void LeftRemote(AVL* &root) /*左旋*/
{
if(root == NULL) return ;
AVL* pMark = NULL, *pNode = NULL;
pMark = root->right; pNode = pMark->right;
/*处理三个孩子关系*/
pMark->right = pNode->left;
pNode->left = pMark;
if(pMark->father){
if(pMark == pMark->father->left){
pMark->father->left = pNode;
}
else{
pMark->father->right = pNode;
}
}
else{
root = pNode;
}
/*处理三个父亲关系*/
if(pMark->right)
pMark->right->father = pMark;
pNode->father = pMark->father;
pMark->father = pNode;
}
void Traver_x(AVL* root){
if(root == NULL) return ;
cout<<root->value<<" ";
Traver_x(root->left);
Traver_x(root->right);
}
void Traver_z(AVL* root){
if(root == NULL) return ;
Traver_z(root->left);
cout<<root->value<<" ";
Traver_z(root->right);
}
void Traver_h(AVL* root){
if(root == NULL) return ;
Traver_h(root->left);
Traver_h(root->right);
cout<<root->value<<" ";
}
int main()
{
AVL* root = NULL;
Create(root);
Traver_x(root);
cout<<endl;
Traver_z(root);
cout<<endl;
Traver_h(root);
cout<<endl;
RightRemote(root);
Traver_x(root);
cout<<endl;
Traver_z(root);
cout<<endl;
Traver_h(root);
cout<<endl;
system("pause");
return 0;
}