If you want to make money online : Register now

Write an algorithm that accepts a Binary Tree as input and prints the number of leaf nodes to standard output.

, , No Comments

 /* Header-File declaration */
#include<stdio.h>
#include<stdlib.h>

/* Structure declaration */
struct BinaryTree
{
int number;
struct BinaryTree *leftchild;
struct BinaryTree *rightchild;
};
typedef struct BinaryTree NODE;

/* Global variable declaration */
NODE *root, *child, *p;
int num, height=0, count=0;

/* Global function declaration */
void insertNode(int n);

void main()
{
char choice;
root = NULL;
while(1)
{
printf("\n Insert Node ? (Y/N)...");
scanf("%c",&choice);
if(choice == 'N')
break;
else
if(choice == 'Y')
{
printf("\n Enter the Number...");
scanf("%d",&num);
insertNode(num);
if(count > height)
{
height = count;
}
count = 0;
}
else
printf("\n\n Press Only (Y/N)");
}
printf("\n\n Height = %d",height);
}

/* Insert operation and height count */
void insertNode(int n)
{
if(root == NULL)
{
root = (NODE *) malloc(sizeof(NODE));
root->number = n;
root->leftchild = NULL;
root->rightchild = NULL;
}
else
{
child = (NODE *) malloc(sizeof(NODE));
child->number = n;
child->leftchild = NULL;
child->rightchild = NULL;
p = root;
while(p != NULL)
{
/* If number <= root value then goto the left side */
if(n <= p->number)
{
if(p->leftchild == NULL)
{
p->leftchild = child;
count++;
break;
}
else
p = p->leftchild;
}
/* If number > root value then goto the right side */
if(n > p->number)
{
if(p->rightchild == NULL)
{
p->rightchild = child;
count++;
break;
}
else
p = p->rightchild;
}
count++;
}
}
}












0 टिप्पणियाँ:

Post a Comment