Count Non-Leaf nodes in a Binary Tree


Given a Binary tree, count total number of non-leaf nodes in the tree


Input :

Output :2
In the above tree only two nodes 1 and 2 are non-leaf nodes

We recursively traverse the given tree. While traversing, we count non-leaf nodes in left and right subtrees and add 1 to the result.

// CPP program to count total number of
// non-leaf nodes in a binary tree
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to 
  left child and a pointer to right child */
struct Node {
    int data;
    struct Node* left;
    struct Node* right;

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);

/* Computes the number of non-leaf nodes in a tree. */
int countNonleaf(struct Node* root)
    // Base cases.
    if (root == NULL || (root->left == NULL && 
                         root->right == NULL))
        return 0;

    // If root is Not NULL and its one of its
    // child is also not NULL
    return 1 + countNonleaf(root->left) + 

/* Driver program to test size function*/
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;



Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

1.3 Average Difficulty : 1.3/5.0
Based on 3 vote(s)