jain12

no. of half nodes with recursion

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