平衡二叉树 3374

发布时间:2019年01月25日 阅读:270 次

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct node
{
   int data;
   int d;
   struct node *l,*r;
}tree;
int deep(tree*root)
{
   if(!root)
   return -1;
   else
   return root->d;
}
tree* LL(tree*root)//左左情况进行右旋
{
    tree*p = root->l;
    root->l = p->r;
    p->r = root;
    p->d =max(deep(p->l),deep(p->r))+1;
    root->d = max(deep(root->l),deep(root->r))+1;
    return p;
}
tree* RR(tree*root)
{
    tree*p = root->r;
    root->r = p-> l;
    p->l = root;
    p->d =max(deep(p->l),deep(p->r))+1;
    root->d = max(deep(root->l),deep(root->r))+1;
    return p;
}


tree* LR(tree*root)//左右情况先进行左旋(右右),然后左旋(左左)
{
    root->l = RR(root->l);
    return LL(root);
}
tree* RL(tree*root)
{
    root->r = LL(root->r);
    return RR(root);
}
tree* creat(tree*root,int x)
{
    if(root==NULL)
    {
       root = (tree*)malloc(sizeof(tree));
       root->d = 0;
       root->data = x;
       root->l = root->r = NULL;
    }
    else if(root->data>x)
    {
         root->l = creat(root->l,x);
         if(deep(root->l)-deep(root->r)>1)
         {
             if(root->l->data>x)
             {
                root = LL(root);
             }
             else
             {
                  root = LR(root);
             }
         }

    }
    else if(root->data<=x)
    {
         root->r = creat(root->r,x);
         if(deep(root->r)-deep(root->l)>1)
         {
              if(root->r->data>x)
              {
                  root = RL(root);
              }
              else
                root = RR(root);
         }
    }
    root->d = max(deep(root->l),deep(root->r))+1;//及时更新每个节点的深度
    return root;

}
int main()
{

   int n,i,x;
   scanf("%d",&n);
   tree*root = NULL;
   for(i = 0;i < n;i++)
   {
      scanf("%d",&x);
      root = creat(root,x);
   }
   printf("%d\n",root->data);

  return 0;
}




/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 0ms
Take Memory: 152KB
Submit time: 2017-02-08 15:25:50
****************************************************/


Tag:
相关文章

发表评论: