Count full nodes in a Binary tree (Iterative and Recursive)
Last Updated :
19 Jul, 2022
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 tree is 2
Method: 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 full 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++
// C++ program to count
// full 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, *right;
};
// Function to get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* node)
{
// If tree is empty
if (!node)
return 0;
queue<Node *> q;
// Do level order traversal starting from root
int count = 0; // Initialize count of full nodes
q.push(node);
while (!q.empty())
{
struct Node *temp = q.front();
q.pop();
if (temp->left && temp->right)
count++;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
return count;
}
/* 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);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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 << getfullCount(root);
return 0;
}
Java
// Java program to count
// full nodes in a Binary Tree
// using Iterative approach
import java.util.Queue;
import java.util.LinkedList;
// Class to represent Tree node
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = null;
right = null;
}
}
// Class to count full nodes of Tree
class BinaryTree
{
Node root;
/* Function to get the count of full Nodes in
a binary tree*/
int getfullCount()
{
// If tree is empty
if (root==null)
return 0;
// Initialize empty queue.
Queue<Node> queue = new LinkedList<Node>();
// Do level order traversal starting from root
queue.add(root);
int count=0; // Initialize count of full nodes
while (!queue.isEmpty())
{
Node temp = queue.poll();
if (temp.left!=null && temp.right!=null)
count++;
// Enqueue left child
if (temp.left != null)
{
queue.add(temp.left);
}
// Enqueue right child
if (temp.right != null)
{
queue.add(temp.right);
}
}
return count;
}
public static void main(String args[])
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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.getfullCount());
}
}
Python3
# Python program to count
# full nodes in a Binary Tree
# using iterative approach
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to count full nodes of binary tree
def getfullCount(root):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
queue = []
# Enqueue Root and initialize count
queue.append(root)
count = 0 #initialize count for full nodes
while(len(queue) > 0):
node = queue.pop(0)
# if it is full node then increment count
if node.left is not None and node.right is not None:
count = count+1
# Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
return count
# Driver Program to test above function
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(getfullCount(root))
C#
// C# program to count
// full nodes in a Binary Tree
// using Iterative approach
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;
}
}
// Class to count full nodes of Tree
public class BinaryTree
{
Node root;
/* Function to get the count of full Nodes in
a binary tree*/
int getfullCount()
{
// If tree is empty
if (root == null)
return 0;
// Initialize empty queue.
Queue<Node> queue = new Queue<Node>();
// Do level order traversal starting from root
queue.Enqueue(root);
int count = 0; // Initialize count of full nodes
while (queue.Count != 0)
{
Node temp = queue.Dequeue();
if (temp.left != null && temp.right != null)
count++;
// Enqueue left child
if (temp.left != null)
{
queue.Enqueue(temp.left);
}
// Enqueue right child
if (temp.right != null)
{
queue.Enqueue(temp.right);
}
}
return count;
}
// Driver code
public static void Main(String []args)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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.getfullCount());
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to count
// full nodes in a Binary Tree
// using Iterative approach
// Class to represent Tree node
class Node
{
constructor(item)
{
this.data = item;
this.left = null;
this.right = null;
}
}
let root;
// Function to get the count of full
// Nodes in a binary tree
function getfullCount()
{
// If tree is empty
if (root == null)
return 0;
// Initialize empty queue.
let queue = [];
// Do level order traversal starting from root
queue.push(root);
// Initialize count of full nodes
let count = 0;
while (queue.length != 0)
{
let temp = queue.shift();
if (temp.left != null && temp.right != null)
count++;
// Enqueue left child
if (temp.left != null)
{
queue.push(temp.left);
}
// Enqueue right child
if (temp.right != null)
{
queue.push(temp.right);
}
}
return count;
}
// Driver code
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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(getfullCount());
// This code is contributed by rag2127
</script>
Output:
2
Time Complexity: O(n)
Auxiliary Space : O(n) where, n is number of nodes in given binary tree
Method: Recursive
The idea is to traverse the tree in postorder. If the current node is full, we increment result by 1 and add returned values of left and right subtrees.
C++
// C++ program to count full 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, *right;
};
// Function to get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* root)
{
if (root == NULL)
return 0;
int res = 0;
if (root->left && root->right)
res++;
res += (getfullCount(root->left) +
getfullCount(root->right));
return res;
}
/* 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);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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 << getfullCount(root);
return 0;
}
Java
// Java program to count full nodes in a Binary Tree
import java.util.*;
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, right;
}
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
if (root == null)
return 0;
int res = 0;
if (root.left != null && root.right != null)
res++;
res += (getfullCount(root.left) + getfullCount(root.right));
return res;
}
/* 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);
}
// Driver program
public static void main(String[] args)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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(getfullCount(root));
}
}
Python3
# Python program to count full
# nodes in a Binary Tree
class newNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the count of
# full Nodes in a binary tree
def getfullCount(root):
if (root == None):
return 0
res = 0
if (root.left and root.right):
res += 1
res += (getfullCount(root.left) +
getfullCount(root.right))
return res
# Driver code
if __name__ == '__main__':
""" 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
"""
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(getfullCount(root))
# This code is contributed by SHUBHAMSINGH10
C#
// C# program to count full 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
public class Node
{
public int data;
public Node left, right;
}
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
if (root == null)
return 0;
int res = 0;
if (root.left != null && root.right != null)
res++;
res += (getfullCount(root.left) + getfullCount(root.right));
return res;
}
/* 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);
}
// Driver program
public static void Main()
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
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(getfullCount(root));
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// JavaScript program to count full nodes in a Binary Tree
// A binary tree Node has data, pointer to left
// child and a pointer to right child
class Node
{
constructor()
{
this.data = 0;
this.left = null;
this.right = null;
}
}
// Function to get the count of full Nodes in
// a binary tree
function getfullCount(root)
{
if (root == null)
return 0;
var res = 0;
if (root.left != null && root.right != null)
res++;
res += (getfullCount(root.left) + getfullCount(root.right));
return res;
}
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
function newNode(data)
{
var node = new Node();
node.data = data;
node.left = null;
node.right = null;
return (node);
}
// Driver program
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
var 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(getfullCount(root));
</script>
Output:
2
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read