Count Non-Leaf nodes in a Binary Tree - GeeksforGeeks

18 Jun, 2021
Given a Binary tree, count total number of non-leaf nodes in the treeExamples:  
Input :
Output :2
Explanation
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. 
C++
Java
Python3
C#
Javascript
// 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 thegiven 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) +               countNonleaf(root->right);} /* 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;}
// Java program to count total number of// non-leaf nodes in a binary treeclass GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node {    int data;    Node left;    Node right;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;    return (node);} /* Computes the number of non-leaf nodes in a tree. */static int countNonleaf(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) +                countNonleaf(root.right);} /* Driver program to test size function*/public static void main(String[] args){    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    System.out.println(countNonleaf(root));}}
# Python3 program to count total number# of non-leaf nodes in a binary tree # class that allocates a new node with the#given data and None left and right pointers.class newNode:    def __init__(self,data):        self.data = data        self.left = self.right = None # Computes the number of non-leaf# nodes in a tree.def countNonleaf(root):         # Base cases.    if (root == None or (root.left == None and                         root.right == None)):        return 0     # If root is Not None and its one of     # its child is also not None    return (1 + countNonleaf(root.left) +                countNonleaf(root.right)) # Driver Codeif __name__ == '__main__':     root = newNode(1)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)    print(countNonleaf(root)) # This code is contributed by PranchalK
// C# program to count total number of// non-leaf nodes in a binary treeusing System; class GfG{     /* A binary tree node has data, pointer to    left child and a pointer to right child */    class Node {        public int data;        public Node left;        public Node right;    }     /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */    static Node newNode(int data)    {        Node node = new Node();        node.data = data;        node.left = null;        node.right = null;        return (node);    }     /* Computes the number of non-leaf nodes in a tree. */    static int countNonleaf(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) +                    countNonleaf(root.right);    }     /* Driver code*/    public static void Main(String[] args)    {        Node root = newNode(1);        root.left = newNode(2);        root.right = newNode(3);        root.left.left = newNode(4);        root.left.right = newNode(5);        Console.WriteLine(countNonleaf(root));    }} // This code is contributed by PrinciRaj1992
<script>    // Javascript 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 */    class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */    function newNode(data)    {        let node = new Node(data);        return (node);    }     /* Computes the number of non-leaf nodes in a tree. */    function countNonleaf(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) +                    countNonleaf(root.right);    }         let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    document.write(countNonleaf(root));   // This code is contributed by mukesh07.</script>
Output:  
2
 
YouTubeGeeksforGeeks507K subscribersCount Non-Leaf nodes in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zdAz4duTaE0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
prerna saini
princiraj1992
PranchalKatiyar
mukesh07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Top 50 Tree Coding Problems for Interviews
Find the node with minimum value in a Binary Search Tree
Print Binary Tree in 2-Dimensions
Real-time application of Data Structures
Iterative Postorder Traversal | Set 2 (Using One Stack)
Find maximum (or minimum) in Binary Tree
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Difference between Min Heap and Max Heap