title: How to count the total number of nodes in binary tree
body: <p>I need to count the total number of nodes in binary tree. The problem now arise when I execute this code, it's giving garbage value for total number of nodes. The output of my program is like <code>993814</code>. which should be <code>7</code>.</p>
  
  <p>How to fix this problem? </p>
  
  <pre><code>#include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  
  struct binarytree
  {
      int data;
      struct binarytree * right, * left;
  };
  
  typedef struct binarytree node;
  
  void insert(node ** tree, int val)
  {
      node *temp = NULL;
      if(!(*tree))
      {
          temp = (node *)malloc(sizeof(node));
          temp-&gt;left = temp-&gt;right = NULL;
          temp-&gt;data = val;
          *tree = temp;
          return;
      }
  
      if(val &lt; (*tree)-&gt;data)
      {
          insert(&amp;(*tree)-&gt;left, val);
      }
      else if(val &gt; (*tree)-&gt;data)
      {
          insert(&amp;(*tree)-&gt;right, val);
      }
  
  }
  
  void print_preorder(node * tree)
  {
      if (tree)
      {
          printf("%d\n",tree-&gt;data);
          print_preorder(tree-&gt;left);
          print_preorder(tree-&gt;right);
      }
  
  }
  
  void print_inorder(node * tree)
  {
      if (tree)
      {
          print_inorder(tree-&gt;left);
          printf("%d\n",tree-&gt;data);
          print_inorder(tree-&gt;right);
      }
  }
  
  int count(node *tree)
  {
      int c=0;
  
      if (tree ==NULL)
          return 0;
  
      else
      {
          c += count(tree-&gt;left);
          c += count(tree-&gt;right);
          return c;
      }
  }
  
  void print_postorder(node * tree)
  {
      if (tree)
      {
          print_postorder(tree-&gt;left);
          print_postorder(tree-&gt;right);
          printf("%d\n",tree-&gt;data);
      }
  }
  
  int main()
  {
      node *root;
      node *tmp;
      int c;
  
      root = NULL;
      /* Inserting nodes into tree */
      insert(&amp;root, 9);
      insert(&amp;root, 10);
      insert(&amp;root, 15);
      insert(&amp;root, 6);
      insert(&amp;root, 12);
      insert(&amp;root, 17);
      insert(&amp;root, 2);
  
      /* Printing nodes of tree */
      printf("Pre Order Display\n");
      print_preorder(root);
  
      printf("In Order Display\n");
      print_inorder(root);
  
      printf("Post Order Display\n");
      print_postorder(root);
  
      printf("Number of node %d \n",c);
  
  }
  </code></pre>