Slip 10 - A) Write a ‘C’ program to read ‘n’ integers and store them in a Binary search tree and display the nodes level wise.

Solution:

#include <stdio.h>
#include <stdlib.h>

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

struct node *newnode(int data)
{
    struct node *temp;
    temp= (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    temp->left = NULL;temp->right = NULL;
    return temp;
}

struct node *insertLevelOrder(int arr[],struct node *root,int i,int n)
{
    if(i<n)
    {
        struct 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;
}

void printGivenLevel(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);

void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
     {
printGivenLevel(root, i);
          printf("\n");
     }
}


void printGivenLevel(struct node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}


int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
int lheight = height(node->left);
int rheight = height(node->right);

if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int main()
{
struct node *root = NULL;
     int n,arr[50],i;
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);

printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);

return 0;
}

Post a Comment

0 Comments