The need:
This program counts the total number of nodes in a binary tree and prints that for the user. This count is also known as tree size.
The code:
----------------------------------------------------------
#include<stdio.h> #include<stdlib.h> struct tree_node { int data; struct tree_node *left,*right,*parent; }; typedef struct tree_node node; node * new_node(int x); node * insert_node(node *root, int x); int count_nodes(node *root); int main() { node *root=NULL; int i,x,max; printf("how many numbers do you want to enter in tree?\n"); scanf("%d",&max); printf("Enter %d numbers \n",max); for(i=0;i<max;i++) { scanf("%d",&x); root = insert_node(root, x); } printf("all numbers inserted into the tree\t press enter to count"); fflush(stdin); getchar(); printf("\nThere are total %d nodes in this tree\n",count_nodes(root)); return 0; } node * insert_node(node *root, int x) { if(!root) { root = new_node(x); return root; } if(root->data > x) root->left = insert_node(root->left,x); else root->right = insert_node(root->right,x); return root; } int count_nodes(node *root) { if(!root) return 0; else return(count_nodes(root->left) + 1 + count_nodes(root->right)); } node * new_node(int x) { node *furnished; furnished = (node*)malloc(sizeof(node)); furnished->data=x; furnished->left=NULL; furnished->right=NULL; furnished->parent=NULL; return furnished; }
----------------------------------------------------------
Approach: The approach is simple. We have to go by recursion. if the root is null(means there is no tree) then number of nodes are 0. Otherwise if root is not null(the tree exists), the total number of nodes will be(number of nodes in left subtree + number of nodes in right subtree + 1 )
Here recursive function count_nodes does the job very well.
No comments:
Post a Comment
feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply