Solution:
#include<stdio.h>
#include<stdlib.h>
struct binary_tree
{
    int info;
    struct binary_tree *left;
    struct binary_tree *right;
};
typedef struct binary_tree NODE;
NODE *node=NULL;
NODE *newnode(int data)
{
    NODE *temp;
    temp= (NODE*)malloc(sizeof(NODE));
    temp->info = data;
    temp->left = NULL;temp->right = NULL;
    return temp;
}
NODE *insertLevelOrder(int arr[],NODE *root,int i,int n)
{
    if(i<n)
    {
        NODE *temp=newnode(arr[i]);
        root=temp;
        root->left=insertLevelOrder(arr,root->left,(2*i)+1,n);
        root->right=insertLevelOrder(arr,root->right,(2*i)+2,n);
    }
    return root;
}
unsigned int count(NODE *node)
{
    if(node==NULL)
    {
        return 0;
    }
    else
    {
        return 1+count(node->left)+count(node->right);
    }
}
unsigned int getLeafCount(NODE *node) 
{ 
  if(node == NULL)        
    return 0; 
  if(node->left == NULL && node->right==NULL)       
    return 1;
  else              
    return getLeafCount(node->left)+ 
           getLeafCount(node->right);       
}
int degree(NODE *node)
{
    if(node==NULL)
    {
        printf("Tree is empty\n");
    }
    else if(node->left==NULL && node->right==NULL)
    {
        return 0;
    }
    else if(node->left && node->right)
    {
        return 2;
    }
    else if(node->left || node->right)
    {
        return 1;
    }
}
int main()
{
     int data,ch,i,n,arr[50],count1,count2,count3;
     NODE *root=NULL;
     while (ch!=5)
     {
          printf("\n\n1.Insertion in Binary Search Tree");
          printf("\n2.Total number of nodes");
          printf("\n3.Degree of tree");
          printf("\n4.Leaf nodes");
          printf("\n5.Exit");
          printf("\nEnter your Choice: \n");
          scanf("%d", &ch);
          switch (ch)
          {
                case 1: printf("\nEnter size of tree: " );
                        scanf("%d", &n);
                        printf("\nEnter the Values to Create Binary tree\n");
                        for(i=0; i<n; i++)
                        {
                           scanf("%d",&arr[i]);                              
                        }
                        root=insertLevelOrder(arr,root,0,n);
                        break;
                case 2: count1=count(root);
                        printf("Number of nodes :%d\n",count1);
                        break;
                case 3: count2=degree(root);
                        printf("Degree of tree :%d\n",count2);
                        break; 
                case 4: count3=getLeafCount(root);
                        printf("Number of Leaf nodes :%d\n",count3);
                        break;
                case 5: exit(0);
                default: printf("\nSelect a valid option\n");
                        break;
          }
     }
}
0 Comments