Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in c that counts the number of nodes in a binary tree, count the

ID: 3785652 • Letter: W

Question

Write a program in c that counts the number of nodes in a binary tree, count the nodes in the right sub-tree, and count the nodes in the left sub-tree. Ask the user to enter their name and grade for the midterm exam. Find out if the tree is unbalanced or balanced. You're building the tree based on the results of the midterm. The root node for the binary tree is 90.

Use this equation to find if the tree is balanced.

Use this as an example of a tree not being balanced.

gary 90
michael 100
jerry 88
steven 0
shauratt 99
Kris 60
Mary 99
larry 71
tarik 88
joey 100

Output: This binary tree is not balanced.

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>


struct leafn {
struct leafn * l;

int val;
struct leafn * r;
};

typedef struct leafn n;

void disp(n *);

void count_leaf_right(n *);
void const_tree();
void count_leaf_left(n *);
n *new, *list, *rt;
int countl = 0, countr = 0;
n * create(); //to create nodes of tree
{
new = (n *)malloc(sizeof(n));
new->l = NULL;
new->r = NULL;
}
//constructing a tree with node=90
void const_tree()
{
rt = create();
rt->val = 90;
rt->l = create();
rt->l->val = 100;
rt->r = create();
rt->r->val = 88;
rt->l->l = create();
rt->l->l->val = 0;
rt->l->r = create();
rt->l->r->val = 99;
rt->l->r->r = create();
rt->l->r->r->val = 60;
rt->l->l->l = create();
rt->l->l->l->val = 99;
rt->l->l->r = create();
rt->l->l->r->val = 71;
rt->l->l->l = create();
rt->l->l->l->val = 88;
rt->l->l->r = create();
rt->l->l->r->val = 100;
}
//left side nodes of tree
void count_leaf_left(n * list)
{
if (list == NULL)
{
return;
}
if (list->l == NULL)
{
countl++;
}
count_leaf(list->l);
}
//right side nodes of tree
void count_leaf_right(n * list)
{
if (list == NULL)
{
return;
}
if (list->r == NULL)
{
countr++;
}
count_leaf(list->r);
}
void disp(n * list)
{
if (list == NULL)
{
return 0;
}
disp(list->l);

printf(" ->%d", list->val);

disp(list->r);

printf(" ->%d", list->val);
}

void main()
{
const_tree();
disp(rt);
count_leaf_left(rt);
count_leaf_right(rt);
printf("leaf nodes on the left side of tree are = %d",countl);
printf("leaf nodes on the right side of tree are = %d",countr);

if((countl-countr)<= 1 )

   {
   printf("This binary tree is balanced. ");
   {
else
   {
   printf("This binary tree is Not balanced. ");
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote