Write C code to count the number of leaves in a tree

In a binary search tree, a node which contains blank left and right children’s that particular node is called as a leaf node in a tree. Here We are going give a c program for finding the number of leaf nodes in a tree.
In a c Program we explained recursively how to find leaf nodes.

leaf nodes in binary search tree

#include

typedef struct node
{
  int value;
  int visited;
  int bf;
  struct node *right;
  struct node *left;
}mynode;

void count_leaf(mynode *node)
{
  if(node == NULL)
    return 0;
  if(node->left == NULL && node->right==NULL)
    return 1;
  else
    return getLeafCount(node->left)+
           getLeafCount(node->right);
   }
}

Complexity of the program will be same as of tree traversal.
If any one can write non recursive program . Please do post.

One Thought on “Write C code to count the number of leaves in a tree

  1. *******************************************************************************************************
    JAVA CODE FOR COUNTING LEAFNODES
    *******************************************************************************************************
    static int t=0;
    public static bnode totalLeafNode(bnode root)
    {
    if(root==null)
    {
    return root;
    }
    if(root.left==null && root.right==null)
    {
    t++;
    System.out.println(“t = “+t);
    }
    else
    {
    totalLeafNode(root.left);
    totalLeafNode(root.right);
    }
    return root;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation