Number of Nodes in the binary tree.
Below is the source code of checking the number of Nodes in the binary tree.
If you need any explanation then please feel free to contact me on my email i.e harshprasadaju@gmail.com.
Thankyou.
#include <stdio.h>
#include <stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
struct tree *Createnode(int data)
{
struct tree *nd = (struct tree *)malloc(sizeof(struct tree));
nd->left = NULL;
nd->right = NULL;
nd->data = data;
return nd;
}
void preOrderTraversal(struct tree *root)
{
if (root != NULL)
{
printf("%d ", root->data);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
}
void postOrderTraversal(struct tree *root)
{
if (root != NULL)
{
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%d ", root->data);
}
}
void inOrderTraversal(struct tree *root)
{
if (root != NULL)
{
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}
int noOfNodes(struct tree *root)
{
if (root == NULL)
return 0;
else
return 1 + noOfNodes(root->left) + noOfNodes(root->right);
}
int main()
{
struct tree *t = Createnode(4);
struct tree *t1 = Createnode(1);
struct tree *t2 = Createnode(6);
struct tree *t4 = Createnode(5);
struct tree *t5 = Createnode(2);
struct tree *t6 = Createnode(8);
struct tree *t7 = Createnode(9);
t->left = t1;
t->right = t2;
t1->left = t4;
t1->right = t6;
t2->right = t5;
t2->left = t7;
// printf("Preorder traversal of the tree: \n");
// preOrderTraversal(t);
// printf("\n");
// printf("Postorder traversal of the tree: \n");
// postOrderTraversal(t);
// printf("\n");
// printf("Inorder traversal of the tree: \n");
inOrderTraversal(t);
// int k = noOfNodes(t);
printf("\nNumber of nodes in the binary tree is : %d", noOfNodes(t));
return 0;
}
Comments
Post a Comment