top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Count Number of Non Leaf Nodes of a given Tree ?

+6 votes
571 views

How can we count Number of Non Leaf Nodes of a given Tree ?

Example
            40
            /\
           /  \
         20    60
         / \    \
       10  30   80
                 \
                 90

Answer => 4

posted Nov 23, 2013 by Mona Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

We can directly find Internal nodes by using this function(Assuming it as binary tree)

int NonLeafCount(node* node)
{
    if((node == NULL) || (node->left == NULL && node->right==NULL)) return 0;
    else return 1+NonLeafCount(node->left) + NonLeafCount(node->right);
}
answer Nov 25, 2013 by Raghu
+1 vote
unsigned int getLeafCount(struct node* node)
{
  if(node == NULL)       
    return 0;
  if(node->left == NULL && node->right==NULL)      
    return 1;            
  else
    return getLeafCount(node->left)+
           getLeafCount(node->right);      
}

Now subtract it from total number of nodes so same function will serve two purpose count leaf nodes or count non leaf node.

answer Nov 23, 2013 by Harshita
Similar Questions
+5 votes
      40
      /\
     20 60
     /\  \
   10 30  80
      /   /\
     25  70 90
           \
           75

longest path 
25 30 20 40 60 80 70 75 
Answer
    25 ----> 75
+7 votes

Print cousins of a given node (Not sibling) ??

...