Count half nodes in a Binary tree (Iterative and Recursive)
Last Updated :
13 Sep, 2023
Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL.
Input : Root of below tree

Output : 3
Nodes 7, 5 and 9 are half nodes as one of
their child is Null. So count of half nodes
in the above tree is 3
Iterative
The idea is to use level-order traversal to solve this problem efficiently.
1) Create an empty Queue Node and push root node to Queue.
2) Do following while nodeQeue is not empty.
a) Pop an item from Queue and process it.
a.1) If it is half node then increment count++.
b) Push left child of popped item to Queue, if available.
c) Push right child of popped item to Queue, if available.
Below is the implementation of this idea.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
unsigned int gethalfCount( struct Node* node)
{
if (!node)
return 0;
int count = 0;
queue<Node *> q;
q.push(node);
while (!q.empty())
{
struct Node *temp = q.front();
q.pop();
if (!temp->left && temp->right ||
temp->left && !temp->right)
count++;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
return count;
}
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int main( void )
{
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
}
|
Java
import java.util.Queue;
import java.util.LinkedList;
class Node
{
int data;
Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
class BinaryTree
{
Node root;
int gethalfCount()
{
if (root== null )
return 0 ;
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
int count= 0 ;
while (!queue.isEmpty())
{
Node temp = queue.poll();
if (temp.left!= null && temp.right== null ||
temp.left== null && temp.right!= null )
count++;
if (temp.left != null )
queue.add(temp.left);
if (temp.right != null )
queue.add(temp.right);
}
return count;
}
public static void main(String args[])
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node( 2 );
tree_level.root.left = new Node( 7 );
tree_level.root.right = new Node( 5 );
tree_level.root.left.right = new Node( 6 );
tree_level.root.left.right.left = new Node( 1 );
tree_level.root.left.right.right = new Node( 11 );
tree_level.root.right.right = new Node( 9 );
tree_level.root.right.right.left = new Node( 4 );
System.out.println(tree_level.gethalfCount());
}
}
|
Python3
class Node:
def __init__( self ,key):
self .data = key
self .left = None
self .right = None
def gethalfCount(root):
if root is None :
return 0
queue = []
queue.append(root)
count = 0
while ( len (queue) > 0 ):
node = queue.pop( 0 )
if node.left is not None and node.right is None or node.left is None and node.right is not None :
count = count + 1
if node.left is not None :
queue.append(node.left)
if node.right is not None :
queue.append(node.right)
return count
root = Node( 2 )
root.left = Node( 7 )
root.right = Node( 5 )
root.left.right = Node( 6 )
root.left.right.left = Node( 1 )
root.left.right.right = Node( 11 )
root.right.right = Node( 9 )
root.right.right.left = Node( 4 )
print "%d" % (gethalfCount(root))
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
public class BinaryTree
{
Node root;
int gethalfCount()
{
if (root == null )
return 0;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
int count = 0;
while (queue.Count != 0)
{
Node temp = queue.Dequeue();
if (temp.left != null && temp.right == null ||
temp.left == null && temp.right != null )
count++;
if (temp.left != null )
queue.Enqueue(temp.left);
if (temp.right != null )
queue.Enqueue(temp.right);
}
return count;
}
public static void Main()
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(2);
tree_level.root.left = new Node(7);
tree_level.root.right = new Node(5);
tree_level.root.left.right = new Node(6);
tree_level.root.left.right.left = new Node(1);
tree_level.root.left.right.right = new Node(11);
tree_level.root.right.right = new Node(9);
tree_level.root.right.right.left = new Node(4);
Console.WriteLine(tree_level.gethalfCount());
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .data = item;
this .left = null ;
this .right = null ;
}
}
var root;
function gethalfCount()
{
if (root == null )
return 0;
var queue = [];
queue.push(root);
var count = 0;
while (queue.length != 0)
{
var temp = queue.shift();
if (temp.left != null && temp.right == null ||
temp.left == null && temp.right != null )
count++;
if (temp.left != null )
queue.push(temp.left);
if (temp.right != null )
queue.push(temp.right);
}
return count;
}
root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.right = new Node(6);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
document.write(gethalfCount());
</script>
|
Output:
3
Time Complexity: O(n)
Auxiliary Space: O(n)
where, n is number of nodes in given binary tree
Recursive
The idea is to traverse the tree in postorder. If current node is half, we increment result by 1 and add returned values of left and right subtrees.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
unsigned int gethalfCount( struct Node* root)
{
if (root == NULL)
return 0;
int res = 0;
if ((root->left == NULL && root->right != NULL) ||
(root->left != NULL && root->right == NULL))
res++;
res += (gethalfCount(root->left) + gethalfCount(root->right));
return res;
}
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int main( void )
{
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
}
|
Java
import java.util.*;
class GfG {
static class Node
{
int data;
Node left, right;
}
static int gethalfCount(Node root)
{
if (root == null )
return 0 ;
int res = 0 ;
if ((root.left == null && root.right != null ) ||
(root.left != null && root.right == null ))
res++;
res += (gethalfCount(root.left)
+ gethalfCount(root.right));
return res;
}
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = null ;
node.right = null ;
return (node);
}
public static void main(String[] args)
{
Node root = newNode( 2 );
root.left = newNode( 7 );
root.right = newNode( 5 );
root.left.right = newNode( 6 );
root.left.right.left = newNode( 1 );
root.left.right.right = newNode( 11 );
root.right.right = newNode( 9 );
root.right.right.left = newNode( 4 );
System.out.println(gethalfCount(root));
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def gethalfCount(root):
if root = = None :
return 0
res = 0
if (root.left = = None and root.right ! = None ) or \
(root.left ! = None and root.right = = None ):
res + = 1
res + = (gethalfCount(root.left) + \
gethalfCount(root.right))
return res
root = newNode( 2 )
root.left = newNode( 7 )
root.right = newNode( 5 )
root.left.right = newNode( 6 )
root.left.right.left = newNode( 1 )
root.left.right.right = newNode( 11 )
root.right.right = newNode( 9 )
root.right.right.left = newNode( 4 )
print (gethalfCount(root))
|
C#
using System;
class GfG
{
public class Node
{
public int data;
public Node left, right;
}
static int gethalfCount(Node root)
{
if (root == null )
return 0;
int res = 0;
if ((root.left == null && root.right != null ) ||
(root.left != null && root.right == null ))
res++;
res += (gethalfCount(root.left)
+ gethalfCount(root.right));
return res;
}
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = null ;
node.right = null ;
return (node);
}
public static void Main()
{
Node root = newNode(2);
root.left = newNode(7);
root.right = newNode(5);
root.left.right = newNode(6);
root.left.right.left = newNode(1);
root.left.right.right = newNode(11);
root.right.right = newNode(9);
root.right.right.left = newNode(4);
Console.WriteLine(gethalfCount(root));
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .left = null ;
this .right = null ;
this .data = data;
}
}
function gethalfCount(root)
{
if (root == null )
return 0;
let res = 0;
if ((root.left == null && root.right != null ) ||
(root.left != null && root.right == null ))
res++;
res += (gethalfCount(root.left) +
gethalfCount(root.right));
return res;
}
function newNode(data)
{
let node = new Node(data);
return (node);
}
let root = newNode(2);
root.left = newNode(7);
root.right = newNode(5);
root.left.right = newNode(6);
root.left.right.left = newNode(1);
root.left.right.right = newNode(11);
root.right.right = newNode(9);
root.right.right.left = newNode(4);
document.write(gethalfCount(root));
</script>
|
Output :
3
Time Complexity: O(n)
Auxiliary Space: O(n)
where, n is number of nodes in given binary tree
Similar Articles:
This article is contributed by Mr. Somesh Awasthi and Rakesh Kumar.
Similar Reads
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above t
12 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
7 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
Count Non-Leaf nodes in a Binary Tree
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 nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
10 min read
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
7 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
Construct a Binary Tree in Level Order using Recursion
Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion. Examples Given an array arr[] = {15, 10, 20, 8, 12, 16, 25} Approach: Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on th
10 min read
Print and remove leaf nodes of given Binary Tree on each iteration
Given a binary tree, the task is to: Print all the leaf nodes and then delete them all. Repeat this process till the tree becomes empty. Examples: Input: 1 /. \ 2 3 / \ 4 5 Output: Iteration 1: 4 5 3Iteration 2: 2Iteration 3: 1Explanation: The leaf nodes initially were 4, 5 and 3.When those were del
7 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
Get level of a node in binary tree | iterative approach
Given a Binary Tree and a key, write a function that returns level of the key. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function s
10 min read