Calculate Size of a tree

PROBLEM :

Given a binary tree, count number of nodes in it. For example, count of node in below tree is 4.

        1
     /      \
   10      39
  /
5

Input:
The task is to complete the method which takes one argument, root of Binary Tree. The struct Node has a data part which stores the data, pointer to left child and pointer to right child.
There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should return count of nodes in tree.

Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000


--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* Tree node structure  used in the program
 struct Node
 {
     int data;
     struct Node* left;
     struct Node* right;
}; */

/* Computes the number of nodes in a tree. */


int getSize(struct Node* root)
{
   if(root==NULL)
    return 0 ;
   
    return(getSize(root->left)+getSize(root->right)+1) ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )