【题意】
给出一个AVL树的添加节点顺序,输出最后得到的树的根对应的值
【思路】
直接模拟即可,纯属考察概念
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct node{
int value;
node *left;
node *right;
node(int v):value(v),left(NULL),right(NULL){};
node():left(NULL),right(NULL){};
}BiNode;
int getHeight(BiNode *T){
if(T==NULL){
return 0;
}
return max(getHeight(T->left),getHeight(T->right))+1;
}
bool isBalanced(BiNode *T){
int lHeight,rHeight;
lHeight = getHeight(T->left);
rHeight = getHeight(T->right);
return abs(lHeight-rHeight)<=1;
}
BiNode *LL(BiNode *a){
BiNode *b;
b = a->left;
a->left = b->right;
b->right = a;
return b;
}
BiNode *RR(BiNode *a){
BiNode *b;
b = a->right;
a->right = b->left;
b->left = a;
return b;
}
BiNode *LR(BiNode *a){
a->left = RR(a->left);
return LL(a);
}
BiNode *RL(BiNode *a){
a->right = LL(a->right);
return RR(a);
}
BiNode *insertNode(BiNode *root, int num){
if(root==NULL){
root = new BiNode(num);
return root;
}
else if(num<root->value){
root->left = insertNode(root->left, num);
if(!isBalanced(root)){
//LL
if(num<root->left->value){
root = LL(root);
}
//LR
else{
root = LR(root);
}
}
}
else{
root->right = insertNode(root->right, num);
if(!isBalanced(root)){
//RL
if(num<root->right->value){
root = RL(root);
}
//RR
else{
root = RR(root);
}
}
}
return root;
}
int main(){
int n;
BiNode *head = NULL;
cin >> n;
for(int i=0; i<n; i++){
int num;
cin >> num;
head = insertNode(head, num);
}
cout << head->value;
system("pause");
return 0;
}