数据结构学习笔记(五)

习题:平衡二叉树。
Root of AVL Tree

总结

注意弄清楚:

  1. 为什么要对二叉搜索树进行平衡操作
  2. 平衡二叉树是怎样旋转的。基本旋转操作有哪些。

这里写图片描述

这里写图片描述

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

//定义平衡二叉树
typedef int DataType;
typedef struct AVLNode *position;
typedef position AVLTree;
typedef struct AVLNode {
  DataType data;
  AVLTree left;
  AVLTree right;
  int Height;
};

//读入数据,建立平衡二叉树
int Max(int a, int b) { return a > b ? a : b; }

int GetHeight(AVLTree T) {
  int LH, RH, MAXH;
  if (T) {
    LH = GetHeight(T->left);
    RH = GetHeight(T->right);
    MAXH = LH > RH ? LH : RH;
    return MAXH + 1;
  } else
    return 0;
}

AVLTree SingleLeftRotation(AVLTree T) {
  AVLTree B;
  B = T->left;
  T->left = B->right;
  B->right = T;
  T->Height = Max(GetHeight(T->left), GetHeight(T->right)) + 1;
  B->Height = Max(GetHeight(B->left), T->Height) + 1;
  return B;
}

AVLTree SingleRightRotation(AVLTree T) {
  AVLTree C;
  C = T->right;
  T->right = C->left;
  C->left = T;
  T->Height = Max(GetHeight(T->left), GetHeight(T->right)) + 1;
  C->Height = Max(GetHeight(T->left), T->Height) + 1;
  return C;
}

AVLTree DoubelLeftRightRotation(AVLTree A) {
  A->left = SingleRightRotation(A->left);
  return SingleLeftRotation(A);
}

AVLTree DoubleRightLeftRotation(AVLTree A) {
  A->right = SingleLeftRotation(A->right);
  return SingleRightRotation(A);
}

AVLTree Insert(AVLTree T, DataType X) {
  if (!T) {
    T = (AVLTree)malloc(sizeof(struct AVLNode));
    T->data = X;
    T->left = T->right = NULL;
    T->Height = 0;
  } else if (X < T->data) {
    T->left = Insert(T->left, X);
    if (GetHeight(T->left) - GetHeight(T->right) == 2) {
      if (X < T->left->data)
        T = SingleLeftRotation(T);
      else
        T = DoubelLeftRightRotation(T);
    }
  } else if (X > T->data) {
    T->right = Insert(T->right, X);
    if (GetHeight(T->right) - GetHeight(T->right) == -2) {
      if (X > T->right->data)
        T = SingleRightRotation(T);
      else
        T = DoubleRightLeftRotation(T);
    }
  }
  T->Height = Max(GetHeight(T->left), GetHeight(T->right)) + 1;
  return T;
}

void PreOrderPrintTree(AVLTree T) {
  if (!T)
    return;
  printf("%d  ", T->data);
  PreOrderPrintTree(T->left);
  PreOrderPrintTree(T->right);
}

int main() {
  int i, N, num[22];
  scanf("%d\n", &N);
  AVLTree T = NULL;

  for (i = 0; i < N; i++) {
    cin >> num[i];
  }
  for (i = 0; i < N; i++)
    T = Insert(T, num[i]);

  printf("%d  \n", T->data);

  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值