adplus-dvertising

C Program to Find the Number of Nodes in a Binary Tree

frame-decoration

C Program to Find the Number of Nodes in a Binary Tree

Problem Description

This C Program finds the number of nodes in a Binary tree.

C Program to Find the Number of Nodes in a Binary Tree - Source code
     
                
  /*
 * C Program to Find the Number of Nodes in a Binary Tree
 */

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

struct bt_node
{
    int value;
    struct bt_node *l;
    struct bt_node *r;
};



typedef struct bt_node node;
node *ptr, *root = NULL;

void create_binary();
void pre_order(node *);
int count(node*);
node* add(int);

int  main()
{
    int c;

    create_binary();
    pre_order(root);
    c = count(root);
    printf("\nNumber of nodes in binary tree are:%d\n", c);
}

void create_binary()
{
    root = add(50);
    root->l = add(20);
    root->r = add(30);
    root->l->l = add(70);
    root->l->r = add(80);
    root->l->l->l = add(10);
    root->l->l->r = add(40);
    root->l->r->r = add(60);
}

/* Add the node to binary tree */
node* add(int val)
{
    ptr = (node*)malloc(sizeof(node));
    if (ptr == NULL)
    {
        printf("Memory was not allocated");
        return;
    }
    ptr->value = val;
    ptr->l = NULL;
    ptr->r = NULL;
    return ptr;
}

/* counting the number of nodes in a tree */
int count(node *n)
{
    int c = 1;

    if (n == NULL)
        return 0;
    else
    {
        c += count(n->l);
        c += count(n->r);
        return c;
     }
}

/* Displaying the nodes of tree using preorder traversal*/
void pre_order(node *t)
{
    if (t != NULL)
    {
        printf("%d->", t->value);
        pre_order(t->l);
        pre_order(t->r);
    }
 }

     
      

Program Output

50->20->70->10->40->80->60->30->
Number of nodes in binary tree are:8