Count Non-Leaf nodes in a Binary Tree
Last Updated :
03 Apr, 2023
Given a Binary tree, count the total number of non-leaf nodes in the tree
Examples:
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
Implementation:
C++
// 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) +
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
// Java program to count total number of
// non-leaf nodes in a binary tree
class GfG {
/* A binary tree node has data, pointer to
left child and a pointer to right child */
static class Node {
int data;
Node left;
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 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
# 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 Code
if __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#
// C# program to count total number of
// non-leaf nodes in a binary tree
using 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
JavaScript
<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>
Time Complexity: O(N)
Space Complexity: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.
Another Approach(Iterative):
The given problem can be solved by using the Level Order Traversal.
Follow the steps below to solve the problem:
1) Create a queue(q) and initialize count variable with 0, and store the nodes in q along wise level order and iterate for next level.
2) Perform level order traversal and check if current node is a non-leaf node(have right or left any one child) then increment the count variable.
3) After completing the above steps, return count variable.
Below is the implementation of above approach:
C++
// C++ implementation to find non-leaf
// count of a given Binary tree
#include <bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node{
int data;
struct Node* left;
struct Node* right;
};
// utility function to get the new node
Node* newNode(int data){
Node *new_node = new Node();
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
// function to get count of non-leaf nodes
int getLeafCount(Node* root){
// initializing queue for level order traversal
queue<Node*> q;
q.push(root);
// initializing count variable
int count = 0;
while(!q.empty()){
Node* temp = q.front();
q.pop();
if(temp->left != NULL || temp->right != NULL)
count++;
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
return count;
}
// driver code to test above 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);
// function call
cout << "Non-Leaf count of the tree is : "<< getLeafCount(root) << endl;
return 0;
}
// THIS CODE IS CONTRIBUTED BY KIRIT AGARWAL(KIRTIAGARWAL23121999)
Java
// Java implementation to find non-leaf
// count of a given Binary tree
import java.util.LinkedList;
import java.util.Queue;
// class to represent the tree node
class Node{
public int data;
public Node left, right;
public Node(int data){
data = data;
left = right = null;
}
}
public class BinaryTree{
// utility function to get the new node
static Node newNode(int data){
return new Node(data);
}
// function to get count of non-leaf nodes
static int getLeafCount(Node root){
// initializing queue for level order traversal
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int count = 0;
while(!q.isEmpty()){
Node temp = q.poll();
if(temp.left != null || temp.right != null){
count++;
}
if(temp.left != null) q.add(temp.left);
if(temp.right != null) q.add(temp.right);
}
return count;
}
// driver code to test above 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);
// function call
System.out.println("Non-leaf count of the tree is : " + getLeafCount(root));
}
}
Python3
# Python program to find non-leaf
# count of a given binary tree
# a binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to get the new node
def newNode(data):
return Node(data)
# function to get count of non-leaf nodes
def getLeafCount(root):
# initializing queue for level order traversal
q = []
q.append(root)
# initializing count variable
count = 0
while(len(q) > 0):
temp = q.pop(0)
if(temp.left is not None or temp.right is not None):
count += 1
if(temp.left is not None):
q.append(temp.left)
if(temp.right is not None):
q.append(temp.right)
return count
# driver code to test above function
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
# function call
print("Non-Leaf count of the tree is :", end=" ")
print(getLeafCount(root))
C#
// C# implementation to find non-leaf
// count of a given binary tree
using System;
using System.Collections.Generic;
// class to represent tree node
public class Node{
public int data;
public Node left, right;
public Node(int item){
data = item;
left = null;
right = null;
}
}
public class BinaryTree
{
// utitliry function to get the new node
static Node newNode(int data){
return new Node(data);
}
// function to get count of non-leaf nodes
static int getLeafCount(Node root)
{
// intiializing queue for level order traversal
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int count = 0;
while(q.Count != 0){
Node temp = q.Dequeue();
if(temp.left != null || temp.right != null) count++;
if(temp.left != null) q.Enqueue(temp.left);
if(temp.right != null) q.Enqueue(temp.right);
}
return count;
}
// driver program to test above function
public static void Main(){
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
// function call
Console.WriteLine("Non-Leaf count of the tree is : " + getLeafCount(root));
}
}
JavaScript
// JavaScript implementation to find non-leaf
// count of a given binary tree
// a binary tree node
class Node{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
// utility function to get the new node
function newNode(data){
return new Node(data);
}
// function to get the count of non-leaf nodes
function getLeafCount(root)
{
// initializing queue for level order traversal
let q = [];
q.push(root);
// initializing the count variable
let count = 0;
while(q.length > 0){
let temp = q.shift();
if(temp.left != null || temp.right != null) count++;
if(temp.left) q.push(temp.left);
if(temp.right) q.push(temp.right);
}
return count;
}
// driver code to test above functions
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
// function call
console.log("Non-Leaf count of the tree is: "+getLeafCount(root));
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
OutputNon-Leaf count of the tree is : 2
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.
Similar Reads
Program to count leaf nodes in a binary tree
Given a Binary Tree, the task is to count leaves in it. A node is a leaf node if both left and right child nodes of it are NULL. Example:Input: Output: 3Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.Input: Output: 3Explanation: Three leaf nodes are 4, 6 a
7 min read
Iterative program to count leaf nodes in a Binary Tree
Given a Binary Tree, the task is to count leaves in it. A node is a leaf node if both left and right child nodes of it are NULL.Example:Input: Output: 3Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.Input: Output: 3Explanation: Three leaf nodes are 4, 6 an
7 min read
Count number of nodes in a complete Binary Tree
Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree. Examples: Input: Output: 7 Input: Output: 5 Native Approach: The simple approach to solving the given tree is to perform the DFS Traversal on the given tree and cou
15+ min read
Print cousins of a given node in Binary Tree
Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 The idea to first find level of given node using the approach discussed here. Once we hav
15+ min read
Count balanced nodes present in a binary tree
Given a binary tree, the task is to count the number of balanced nodes in the given tree. Balanced nodes of a binary tree are defined as the nodes which contains both left and right subtrees with their respective sum of node values equal. Examples: Input: 9 / \ 2 4 / \ \ -1 3 0 Output: 1Explanation:
7 min read
Pairwise Swap leaf nodes in a binary tree
Given a binary tree, we need to write a program to swap leaf nodes in the given binary tree pairwise starting from left to right as shown below. Tree before swapping: Tree after swapping: The sequence of leaf nodes in original binary tree from left to right is (4, 6, 7, 9, 10). Now if we try to form
11 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
7 min read
Sum of all leaf nodes of binary tree
Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
5 min read
Count all K Sum Paths in Binary Tree
Given a binary tree and an integer k, the task is to count the number of paths in the tree such that the sum of the nodes in each path equals k. A path can start from any node and end at any node and must be downward only.Examples:Input: k = 7 Output: 3Table of Content[Naive Approach] By Exploring A
15+ min read
Sum of leaf nodes at each horizontal level in a binary tree
Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree. Examples: Input: Output:0063012Explanation:Level 1: No leaf node, so sum = 0Level 2: No leaf node, so sum = 0Level 3: One leaf node: 6, so sum = 6 Level 4: Three leaf nodes: 9, 10, 11, so sum = 30Level 5
14 min read