Count Leaves in Binary Tree

 Given a Binary Tree of size N , You have to count leaves in it. For example, there are two leaves in following tree

        1
     /      \
   10      39
  /
5


 

Example 1:


Input:
Given Tree is 
               4
             /   \
            8     10
           /     /   \
          7     5     1
         /
        3 
Output:
3
Explanation: 
Three leaves are 3 , 5 and 1.



c++ implementation:

int countLeaves(Node* root)
{  
   queue<Node*>q; int co=0;
   q.push(root);
  while(!q.empty())
  { Node* t=q.front();
     if(t->left==NULL && t->right==NULL)
      co++;
      q.pop();
    if(t->left!=NULL)
      q.push(t->left);
    if(t->right!=NULL)
      q.push(t->right); 
  }
 return co; 
}


time complexity: O(N)

No comments

darkmode