Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
15
Добавлен:
18.03.2018
Размер:
2.9 Кб
Скачать
#include <iostream>
#include <conio.h>

using namespace std;

struct node
{
      int data;
      int height_left, height_right;
      node * left, * right;
};

typedef struct node * tree;

struct node * new_node (int x)
{
     struct node * t = new node;
     t->data = x;
     t->height_left = t->height_right =  0;
     t->left = t->right = NULL;
     return t;
}

int add_node (tree & t, int x)
{
    if (!t) {t=new_node(x); return 1;}
    if (x==t->data) return 0;
    if (x<t->data)
    {
       if (add_node(t->left,x))
       {
          t->height_left++;
          if (t->height_left>t->height_right) return 1;
       }
       return 0;
    }
    if (add_node(t->right,x))
    {
       t->height_right++;
       if (t->height_right > t->height_left) return 1;
    }
    return 0;
}

void print_sim (tree t)
{
     if (t->left) print_sim(t->left);
     cout<<t->data<<'('<<t->height_left<<'/'<<t->height_right<<")  ";
     if (t->right) print_sim(t->right);
}

void leftrotation (tree & t)
{
     node * temp = t->right;
     t->right = temp->left;
     t->height_right = temp->height_left;
     temp->left=t;
     temp->height_left=1+((t->height_left>t->height_right)?t->height_left:t->height_right);
     t=temp;
}
     
void rightrotation (tree & t)
{
     node * temp = t->left;
     t->left = temp->right;
     t->height_left = temp->height_right;
     temp->right=t;
     temp->height_right=1+((t->height_left>t->height_right)?t->height_left:t->height_right);
     t=temp;
}
     
int balance_tree (tree & t, int bal)
{
     int b;
     b=t->height_left - t->height_right;
     if (t->left)
     {
     	t->height_left=1+balance_tree (t->left, b);
      	b=t->height_left - t->height_right;
     }
     if (t->right)
     {
     	t->height_right=1+balance_tree (t->right, b);
      	b=t->height_left - t->height_right;
     }
     if (b>0 && bal<0 || b>1)
     {
     	rightrotation (t);
	    print_sim (t);
     	cout<<endl;
      	getch();
       	b=t->height_left - t->height_right;
	    balance_tree (t,b);
     }
     else if (b<-1 || b<0 && bal>0)
     {
        leftrotation (t);
        print_sim (t);
        cout<<endl;
        getch();
        b=t->height_left - t->height_right;
        balance_tree (t,b);
     }
     return (t->height_left>t->height_right)?t->height_left:t->height_right;
}

void del_tree (tree t)
{
     if (t->left) del_tree (t->left);
     if (t->right) del_tree (t->right);
     delete t;
}

main()
{
   tree t=NULL;
   int mas[15]={14, 8, 1, 13, 7, 12, 6, 2, 9, 0, 11, 10, 4, 3, 5}, i;
   
   for (i=0; i<15; i++)
   {
      add_node (t, mas[i]);
      print_sim (t);
      cout<<endl;
   }
   print_sim (t);
   getch();
   cout<<endl;
   balance_tree (t,0);
   print_sim (t);
   del_tree (t);
   getch();
   return 0;
}
Соседние файлы в папке Дерево