// L-42 MCS 360 Wed 1 Dec 2010 : write_balance.cpp

/* Give the code to compute the balance of a tree, using the definitions

      typedef struct node tree;
      struct node
      {
         int info;
         tree *left;
         tree *right;
      };

   and the prototype

      void write_balance ( int k, tree *t );
*/
      /* writes the info and balance of every node in inorder traversal,
         k controls the depth of the tree (call with k == 0) */


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

// C style definition of a binary tree of integers :

typedef struct node tree;
struct node
{
   int info;
   tree *left;
   tree *right;
};

tree *insert_number ( tree *t, int i );
// inserts on number in the binary search tree t

tree *insert_numbers ( tree *t, int n);
// inserts n random numbers in a binary seart tree

void write ( int k, tree *t );
// writes the tree, call with k == 0

int depth ( tree *t );
// returns the depth of the tree

int balance ( tree *t );
// returns the balance of the tree

void write_balance ( int k, tree *t );
// writes the tree with the balance at each node, call with k == 0

int main()
{
   tree *t = NULL;
   cout << "give n : "; 
   int n; cin >> n;
   t = insert_numbers(t,n);
   write_balance(0,t);
   return 0;
}

tree *insert_number ( tree *t, int i)
{
   if(t == NULL)
   {
      t = new node;
      t->info = i;
      t->left = NULL;
      t->right = NULL;
   }
   else if(i < t->info)
      t->left = insert_number(t->left,i);
   else
      t->right = insert_number(t->right,i);

   return t;
}

tree *insert_numbers ( tree *t, int n )
{
   srand(time(NULL));
   for(int i=0; i<n; i++)
   {
      int r = rand() % 100;
      t = insert_number(t,r);
   }
   return t;
}

int depth ( tree *t )
{
   if(t == NULL)
      return -1;
   else if(t->left == NULL)
      return 1+depth(t->right);
   else if(t->right == NULL)
      return 1+depth(t->left);
   else
   {
      int L = depth(t->left);
      int R = depth(t->right);
      if(L > R)
         return L + 1;
      else
         return R + 1;
   }
}

int balance ( tree *t )
{
   if(t == NULL)
      return 0;
   else
      return depth(t->left) - depth(t->right);
}

void write ( int k, tree *t )
{
   if(t != NULL)
   {
      for(int i=0; i<k; i++) cout << "  ";
      cout << t->info << endl;
      write(k+1,t->left);
      write(k+1,t->right);
   }
}

void write_balance ( int k, tree *t )
{
   if(t != NULL)
   {
      for(int i=0; i<k; i++) cout << "  ";
      cout << t->info 
           << " balance : " << balance(t) << endl;
      write_balance(k+1,t->left);
      write_balance(k+1,t->right);
   }
}

