0% found this document useful (0 votes)
4 views5 pages

Count Leaf and Total Nodes in C Tree

This C program defines a binary tree and includes functions to count the number of leaf nodes and the total number of nodes in the tree. It creates a sample tree structure with nodes and prints the counts of leaf nodes and total nodes. The program utilizes recursion to traverse the tree for counting purposes.

Uploaded by

pawargayatri812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Count Leaf and Total Nodes in C Tree

This C program defines a binary tree and includes functions to count the number of leaf nodes and the total number of nodes in the tree. It creates a sample tree structure with nodes and prints the counts of leaf nodes and total nodes. The program utilizes recursion to traverse the tree for counting purposes.

Uploaded by

pawargayatri812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

/* C Program to find the number of leaf nodes in a Tree,count total no of

nodes */

#include <stdio.h>

#include <stdlib.h>

Struct node

Int info;

Struct node* left, *right;

};

Struct node* createnode(int key)

Struct node* newnode = (struct node*)malloc(sizeof(struct node));

Newnode->info = key;

Newnode->left = NULL;

Newnode->right = NULL;

Return(newnode);

Int count = 0;

Int leafnodes(struct node* newnode)

If(newnode != NULL)

Leafnodes(newnode->left);

If((newnode->left == NULL) && (newnode->right == NULL))

Count++;
}

Leafnodes(newnode->right);

Return count;

Int count_number_of_nodes(struct node* newnode)

// int count1=0;

// if there is no node.

If (newnode == NULL)

Return 0;

// count number of nodes on the left.

Int left = count_number_of_nodes(newnode->left);


// count number of nodes on the right.

Int right = count_number_of_nodes(newnode->right);

// 1 -> to take into account the current node.

Return left + right + 1;

Int main()

Struct node *newnode = createnode(40);

Newnode->left = createnode(22);
Newnode->right = createnode(63);

Newnode->left->left = createnode(16);

Newnode->left->right = createnode(39);

Newnode->left->right->left = createnode(13);

Newnode->right->right = createnode(75);

Printf(“Number of leaf nodes in first Tree are\t%d\


n”,leafnodes(newnode));

Printf(“Number of nodes in first Tree are\t%d\


n”,count_number_of_nodes(newnode));
Return 0;

You might also like