No.3 平衡二叉树

*理解:AVL
~或者为一棵空树,或者左右子树都为平衡二叉树,并且,左右子树深度之差的绝对值不超过1。
~在我看来,平衡二叉树建立在二叉搜索树的基础上,不过是,加了几个旋转而已。
~博客的解释,真的是各种各样,但我确实是不太理解,后来看到了百度文库,才恍然大悟……
LL、RR、RL、LR的解释
~看到了一篇不错的博客,很棒!
数据结构实验之查找二:平衡二叉树
Time Limit: 400MS Memory Limit: 65536KB
Submit Statistic
Problem Description

根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input

输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output

输出平衡二叉树的树根。
Example Input

5
88 70 61 96 120
Example Output

70
Hint

Author

xam

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
   int data;//数据
   int deep;//树的深度
   struct node * left;
   struct node * right;
};
int height(struct node * root)//返回树的深度
{
   if(root==NULL)
   return -1;
   else
   return root->deep;
}
int max(int a, int b)//最大值
{
  if(a>=b)
  return a;
  else
  return b;
}
struct node * LLchange(struct node * root)
{
   struct node * p;
   p = (struct node *)malloc(sizeof(struct node));
   p = root->left;
   root->left = p->right;
   p->right = root;
   root->deep = max(height(root->left), height(root->right))+1;
   p->deep = max(height(p->left), height(p->right))+1;
   return p;
}
struct node * RRchange(struct node * root)
{
   struct node * p;
   p = (struct node *)malloc(sizeof(struct node));
   p = root->right;
   root->right = p->left;
   p->left = root;
   root->deep = max(height(root->left), height(root->right))+1;
   p->deep = max(height(p->left), height(p->right))+1;
   return p;
}
struct node *RLchange(struct node * root)
{
   root->right = LLchange(root->right);
   return RRchange(root);
}
struct node * LRchange(struct node * root)
{
   root->left = RRchange(root->left);
   return LLchange(root);
}
struct node * creat(struct node * root, int key)//建树并且旋转,保持树的平衡
{
    if(root==NULL)
    {
      root  = (struct node *)malloc(sizeof(struct node));
      root->right = root->left = NULL;
      root->deep = 0;
      root->data = key;
    }
    else if(key<root->data)
    {
      root->left = creat(root->left, key);
      if(height(root->left)-height(root->right)==2)
      {
          if(key<root->left->data)
          root = LLchange(root);
          else
          root = LRchange(root);
      }
    }
    else if(root->data<key)
    {
      root->right = creat(root->right, key);
      if(height(root->right)-height(root->left)==2)
      {
      if(root->right->data<key)
      root = RRchange(root);
      else
      root = RLchange(root);
      }
    }
    root->deep = max(height(root->left), height(root->right))+1;
    return root;
}
int main()
{
   int n, x;
   struct node * root;
   root = (struct node *)malloc(sizeof(struct node));
   root = NULL;
   scanf("%d", &n);
   for(int i=0;i<n;i++)
   {
   scanf("%d",&x);
   root = creat(root, x);
   }
   printf("%d\n", root->data);
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值