A1066 Root of AVL Tree (25分)

一、技术总结

  1. 这是一个平衡二叉树AVL树,就是一个二叉查找树,但是平衡因子不能够超过1。
  2. 这个树的数据结构比一般的要多一个height的参数,用于计算平衡因子,就是用当前结点的左子树的height减去右子树的height。
  3. 对于node* newNode(int data)函数,首先要新建一个结点,然后初始化height参数为1,然后左右子树结点赋值为NULL。
  4. getHeight()函数和updateHeight()函数,后者就是根据当前结点的左右子树结点高度的最大值,然后加一。
  5. getBF()函数,也就是求得结点平衡因子的函数。
  6. 左旋和右旋函数,就是分三步,根据自己理解书写,不能忘记的就是更新结点的高度,最后再把root = temp;
  7. 再就是insert()函数,如果是一般的查找二叉树insert,就比较简单,如果结点为空,然后newNode,一个然后return,如果比当前结点小,就是LL,LR类型,记住左正右负。判断进入后,使用insert函数,接着updateHeight(),然后开始旋转。getBF函数为21型直接右旋(root)和2-1型先左旋(root->lchild),然后再右旋(root);如果是比当前结点大,就是RR,RL型同理可以推出。

二、参考代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 25;
struct node{
    int data, height;
    node *lchild, *rchild;
}*Node;
node* newNode(int data){
    node* Node = new node;
    Node->data = data;
    Node->height = 1;
    Node->lchild = Node->rchild = NULL;
    return Node;
}
int getHeight(node* root){
    if(root == NULL) return 0;
    return root->height;
}
int getBF(node* root){
    return getHeight(root->lchild) - getHeight(root->rchild);
}
void updateHeight(node* root){
    root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void L(node* &root){
    node* temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    updateHeight(root);
    updateHeight(temp);
    root = temp;
}
void R(node* &root){
    node* temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    updateHeight(root);
    updateHeight(temp);
    root = temp;
}
void insert(node* &root, int v){
    if(root == NULL){
        root = newNode(v);
        return;
    }
    if(v < root->data){
        insert(root->lchild, v);
        updateHeight(root);
        if(getBF(root) == 2){
            if(getBF(root->lchild) == 1){
                R(root);
            }else if(getBF(root->lchild) == -1){
                L(root->lchild);
                R(root);
            }
        }
    }else{
        insert(root->rchild, v);
        updateHeight(root);
        if(getBF(root) == -2){
            if(getBF(root->rchild) == -1){
                L(root);
            }else if(getBF(root->rchild) == 1){
                R(root->rchild);
                L(root);
            }
        }
    }
}
/*
node* Create(int data[], int n){
    node* root = NULL;
    for(int i = 0; i < n; i++){
        insert(root, data[i]);
    }
    return root;
}*/
int main(){
    int n;
    scanf("%d", &n);
    int v;
    for(int i = 0; i < n; i++){
        scanf("%d", &v);
        insert(Node, v);
    }
    printf("%d", Node->data);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tsruixi/p/12342606.html