Remember
me?
RegisterForgot Your Password?

Binary tree:Number of nodes,Degree of tree,Leaf nodes,Interior nodes

download : source code

Description :C program to display total number of nodes of binary tree,Degree,Number of leaf nodes,Display interior nodes .

The following code consist of five modules-

1.no of leaf nodes
2.degree of tree
3.leaf nodes
4.interior nodes
5.children of parent

  • In-degree of a node is the number of edges arriving at that node.
  • Out-degree of a node is the number of edges leaving that node.
  • The root is the only node in the tree with In-degree = 0.
  • All the leaf nodes have Out-degree = 0.

Code :

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct bintree
{
int info;
struct bintree *left;
struct bintree *right;
};
int count=0;
int flag = 0;
void main()
{
struct bintree *root,*p;
int ch,x,key;
char ans;
struct bintree * insert(struct bintree *,int);
void traverse(struct bintree *);
void count_leaf(struct bintree *);
void interior_nodes(struct bintree *);
clrscr();
root = NULL;
do
{
printf(“\n1.Insert a Node”);
printf(“\n2.Traverse\n3.No of Nodes “);
printf(“\n4.Leaf Nodes of Tree\n5.Interior Nodes”);
printf(“\n6.Exit”);
printf(“\nEnter your choice::”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“\n\n\t\tEnter the information::”);scanf(“%d”,&x);
root = insert(root,x);
break;
case 2:
traverse(root);
break;
case 3:
count = 0;
traverse(root);
printf(“\n\n\t\tThe no of nodes = %d”,count);
break;
case 4:
count = 0;
count_leaf(root);
printf(“\n\n\t\tThe no of leaf nodes are = %d”,count);
break;
case 5 :
count = 0;flag = 0;
interior_nodes(root);
printf(“\n\n\t\tThe no of interior nodes are = %d”,count);
break;
case 6:
break;
default :
printf(“\n\n\t\tInvalid choice “);
}
}while(ch != 6);
getch();
}

struct bintree * insert(struct bintree *root,int x)
{
struct bintree *p,*q,*curr;
curr = (struct bintree *)malloc(sizeof(struct bintree));
curr->info = x;
curr->left=NULL;
curr->right=NULL;
p=q=root;
if(root == NULL)
{
root = curr;
printf(“\n\n\t\t%d Is inserted at root position “,curr->info);
return root;
}
while(q != NULL)
{
p = q;
if(x < p->info)
q = p->left;
else
q = p->right;
}
if(x < p->info)
{
printf(“\n\n\t\tThe node is inserted at %d’s left”,p->info);
p->left = curr;
}
else
{
printf(“\n\n\t\tThe node is inserted at %d’s right”,p->info);
p->right = curr;
}
return root;
}

void traverse(struct bintree *root)
{
if(root != NULL)
{
traverse(root->left);
printf(“   %d”,root->info);
count++;
traverse(root->right);
}
}
void count_leaf(struct bintree *root)
{
if(root != NULL)
{
if(root->left == NULL && root->right == NULL)
{
count++;
printf(“   %d”,root->info);
}
count_leaf(root->left);
count_leaf(root->right);
}
}

void interior_nodes(struct bintree *root)
{

if(root != NULL)
{
if((root->left != NULL || root->right != NULL) && flag == 1)
{
count++;
printf(“   %d”,root->info);
}
flag = 1;
interior_nodes(root->left);
interior_nodes(root->right);
}
}