浙大版《数据结构(第2版)》题目集- 练习4.2

练习4.2 平衡二叉树的根 (25point(s))

将给定的一系列数字插入初始为空的AVL树,请你输出最后生成的AVL树的根结点的值。

Example:

#include <iostream>
#include <vector>
using namespace std;

typedef int ElemType;
typedef struct TreeNode {
    struct TreeNode *Left;
    struct TreeNode *Right;
    ElemType Elem;
    int      Height;
} *Tree;

typedef struct AVLTree {
    Tree T;
} *AVL;

AVL Init()
{
    AVL t = new AVLTree;
    t->T = NULL;
    return t;
}

int Height(Tree T)
{
    if(T == NULL) return 0;
    return T->Height; 
}

void UpdateHeight(Tree T)
{
    if(T != NULL) T->Height = max(Height(T->Left), Height(T->Right)) + 1;
}

int Weight(Tree T)
{
    return Height(T->Left) - Height(T->Right);
}

void Insert(Tree &T, Tree &n)
{
    if(T == NULL) {
        T = n;
    } else if(T->Elem > n->Elem) {
        Insert(T->Left, n);
        if(Weight(T) >= 2) {
            if(Weight(T->Left) == 1) {
                Tree root = T->Left;
                T->Left = root->Right;
                root->Right = T;
                UpdateHeight(root->Right);
                T = root;
            } else if(Weight(T->Left) == -1) {
                Tree root = T->Left->Right;
                T->Left->Right = root->Left;
                root->Left = T->Left;
                T->Left = root->Right;
                root->Right = T;
                UpdateHeight(root->Left);
                UpdateHeight(root->Right);
                T = root;
            }
        }
    } else {
        Insert(T->Right, n);
        if(Weight(T) <= -2) {
            if(Weight(T->Right) == -1) {
                Tree root = T->Right;
                T->Right = root->Left;
                root->Left = T;
                UpdateHeight(root->Left);
                T = root;
            } else if(Weight(T->Right) == 1) {
                Tree root = T->Right->Left;
                T->Right->Left = root->Right;
                root->Right = T->Right;
                T->Right = root->Left;
                root->Left = T;
                UpdateHeight(root->Left);
                UpdateHeight(root->Right);
                T = root;
            }
        }
    }
    UpdateHeight(T);
}

void Add(AVL T, ElemType elem)
{
    Tree t = new TreeNode;
    t->Elem = elem;
    t->Left = NULL;
    t->Right = NULL;
    t->Height = 0;
    Insert(T->T, t);
}

int main()
{
    AVL T = Init();
    int N;
    cin >> N;
    for(int i = 0; i < N; i++) {
        ElemType x;
        cin >> x;
        Add(T, x);
    }
    cout << T->T->Elem << endl;
    return 0;
}

思路:

考察基本的 LL,LR,RR,RL操作,最后给出根节点的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值