jain12

no.of leaves in a binary tree with recursion

Feb 24th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=NULL;
  11.         right=NULL;
  12.         }
  13.   };
  14.  
  15. int CountLeaves(Node *root){
  16.   if(root==NULL)
  17.         return 0;
  18.   if(root->left==NULL && root->right ==NULL)
  19.     return 1;
  20.   return CountLeaves(root->left)+CountLeaves(root->right);
  21.   }
  22.  
  23. int main(){
  24.   Node *root=NULL;
  25.   Node *newnode=new Node(1);
  26.   root=newnode;
  27.   root->left=new Node(2);
  28.   root->right=new Node(3);
  29.   (root->left)->left=new Node(4);
  30.   (root->right)->right=new Node(5);
  31.   (root->left)->right=new Node(6);
  32.   cout<<CountLeaves(root);
  33.   return 0;
  34.   }
Add Comment
Please, Sign In to add comment