Count Non | CPP program to count total number of non - leaf nodes in a binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Computes the number of non - leaf nodes in a tree . ; Base cases . ; If root is Not NULL and its one of its child is also not NULL ; Driver program to test size function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int countNonleaf ( struct Node * root ) { if ( root == NULL || ( root -> left == NULL && root -> right == NULL ) ) return 0 ; return 1 + countNonleaf ( root -> left ) + countNonleaf ( root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << countNonleaf ( root ) ; return 0 ; }