/*COUNT OF NODES*/
#include<stdio.h>
#include<conio.h>
struct TreeNode
{
int data;struct TreeNode *left,*right;
};
int NoOfNodes=0,NoOfLeafs=0,NoOfChildren=0,
NoOfParents=0,NoOfInteriors=0;
struct TreeNode * createTreeNode(int);
void insertTreeNode(struct TreeNode *,int);
void DisplayTree(struct TreeNode *);
void CountNodes(struct TreeNode *);
struct TreeNode * createTreeNode(int d)
{
struct TreeNode * newnode;
newnode = (struct TreeNode *) malloc (sizeof(struct TreeNode) );
newnode->data=d;
newnode->right=NULL;
newnode->left=NULL;
return newnode;
}
void insertTreeNode(struct TreeNode *root,int child)
{
struct TreeNode *newNode = createTreeNode(child);
if(child<root->data)
{
if( (root->left) == NULL)
{
root->left = newNode;
}
else
{
insertTreeNode(root->left,child);
}
}
else if(child>root->data)
{
if((root->right) == NULL)
{
root->right = newNode;
}
else
{
insertTreeNode(root->right,child);
}
}
else
{
printf("Cannot insert.duplicate data");
}
}
void DisplayTree(struct TreeNode *root)
{
if( root!=NULL )
{
DisplayTree(root->left);
printf("%d ",root->data);
DisplayTree(root->right);
}
}
void CountNodes(struct TreeNode *root)
{
if(root!=NULL)
{
NoOfNodes++;
}
if( ((root->left) == NULL) && ((root->right) == NULL) && (root!=NULL) )
{
NoOfLeafs++;
}
if(root->left!=NULL)
{
CountNodes(root->left);
}
if(root->right!=NULL)
{
CountNodes(root->right);
}
}
void main()
{
struct TreeNode *root=NULL;
int data,ch;
clrscr();
while(1)
{
printf("\nMENU\n1.Insert\n2:Display\n3.Count\n4.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
printf("Enter data:");
scanf("%d",&data);
if(root==NULL)
{
root = createTreeNode(data);
}
else
{
insertTreeNode(root,data);
}
break;
}
case 2:
{
printf("Here is BinaryTree:\n");
DisplayTree(root);
break;
}
case 3:
{
NoOfNodes=0;NoOfLeafs=0;NoOfChildren=0;NoOfParents=0;NoOfInteriors=0;
CountNodes(root);
NoOfChildren=NoOfNodes-1;
NoOfParents=NoOfNodes-NoOfLeafs;
NoOfInteriors=NoOfParents-1;
printf("\nNoOfNodes:%d\nNoOfLeafNodes:%d",NoOfNodes,NoOfLeafs);
printf("\nNoOfParentNodes:%d",NoOfParents);
printf("\nNoOfChildren:%d\nNoOfInteriors:%d",NoOfChildren,NoOfInteriors);
break;
}
case 4:
{
exit(0);
}
default:
{
printf("\nWrong choice\n");
}
}
}
}
/*************************OUTPUT*************************
1.Insert
2:Display
3.Count
4.Exit
Enter your choice:1
Enter data:15
MENU
1.Insert
2:Display
3.Count
4.Exit
Enter your choice:1
Enter data:23
MENU
1.Insert
2:Display
3.Count
4.Exit
Enter your choice:1
Enter data:14
MENU
1.Insert
2:Display
3.Count
4.Exit
Enter your choice:2
Here is BinaryTree:
14 15 23
MENU
1.Insert
2:Display
3.Count
4.Exit
Enter your choice:3
NoOfNodes:3
NoOfLeafNodes:2
NoOfParentNodes:1
NoOfChildren:2
NoOfInteriors:0
*************************************************/
No comments:
Post a Comment