Find Count of Single Valued Subtrees
Last Updated :
04 Oct, 2023
Given a binary tree, write a program to count the number of Single Valued Subtrees. A Single Valued Subtree is one in which all the nodes have same value. Expected time complexity is O(n).
Example:
Input: root of below tree
5
/ \
1 5
/ \ \
5 5 5
Output: 4
There are 4 subtrees with single values.
Input: root of below tree
5
/ \
4 5
/ \ \
4 4 5
Output: 5
There are five subtrees with single values.
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to traverse the tree. For every traversed node, check if all values under this node are same or not. If same, then increment count. Time complexity of this solution is O(n2).
An Efficient Solution is to traverse the tree in bottom up manner. For every subtree visited, return true if subtree rooted under it is single valued and increment count. So the idea is to use count as a reference parameter in recursive calls and use returned values to find out if left and right subtrees are single valued or not.
Below is the implementation of above idea.
C++
// C++ program to find count of single valued subtrees
#include<bits/stdc++.h>
using namespace std;
// A Tree node
struct Node
{
int data;
struct Node* left, *right;
};
// Utility function to create a new node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
bool countSingleRec(Node* root, int &count)
{
// Return true to indicate NULL
if (root == NULL)
return true;
// Recursively count in left and right subtrees also
bool left = countSingleRec(root->left, count);
bool right = countSingleRec(root->right, count);
// If any of the subtrees is not singly, then this
// cannot be singly.
if (left == false || right == false)
return false;
// If left subtree is singly and non-empty, but data
// doesn't match
if (root->left && root->data != root->left->data)
return false;
// Same for right subtree
if (root->right && root->data != root->right->data)
return false;
// If none of the above conditions is true, then
// tree rooted under root is single valued, increment
// count and return true.
count++;
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
int countSingle(Node* root)
{
// Initialize result
int count = 0;
// Recursive function to count
countSingleRec(root, count);
return count;
}
// Driver program to test
int main()
{
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
Node* root = newNode(5);
root->left = newNode(4);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(4);
root->right->right = newNode(5);
cout << "Count of Single Valued Subtrees is "
<< countSingle(root);
return 0;
}
Java
// Java program to find count of single valued subtrees
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class Count
{
int count = 0;
}
class BinaryTree
{
Node root;
Count ct = new Count();
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
boolean countSingleRec(Node node, Count c)
{
// Return false to indicate NULL
if (node == null)
return true;
// Recursively count in left and right subtrees also
boolean left = countSingleRec(node.left, c);
boolean right = countSingleRec(node.right, c);
// If any of the subtrees is not singly, then this
// cannot be singly.
if (left == false || right == false)
return false;
// If left subtree is singly and non-empty, but data
// doesn't match
if (node.left != null && node.data != node.left.data)
return false;
// Same for right subtree
if (node.right != null && node.data != node.right.data)
return false;
// If none of the above conditions is true, then
// tree rooted under root is single valued, increment
// count and return true.
c.count++;
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
int countSingle()
{
return countSingle(root);
}
int countSingle(Node node)
{
// Recursive function to count
countSingleRec(node, ct);
return ct.count;
}
// Driver program to test above functions
public static void main(String args[])
{
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
System.out.println("The count of single valued sub trees is : "
+ tree.countSingle());
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python program to find the count of single valued subtrees
# Node Structure
class Node:
# Utility function to create a new node
def __init__(self ,data):
self.data = data
self.left = None
self.right = None
# This function increments count by number of single
# valued subtrees under root. It returns true if subtree
# under root is Singly, else false.
def countSingleRec(root , count):
# Return False to indicate None
if root is None :
return True
# Recursively count in left and right subtrees also
left = countSingleRec(root.left , count)
right = countSingleRec(root.right , count)
# If any of the subtrees is not singly, then this
# cannot be singly
if left == False or right == False :
return False
# If left subtree is singly and non-empty , but data
# doesn't match
if root.left and root.data != root.left.data:
return False
# same for right subtree
if root.right and root.data != root.right.data:
return False
# If none of the above conditions is True, then
# tree rooted under root is single valued,increment
# count and return true
count[0] += 1
return True
# This function mainly class countSingleRec()
# after initializing count as 0
def countSingle(root):
# initialize result
count = [0]
# Recursive function to count
countSingleRec(root , count)
return count[0]
# Driver program to test
"""Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5
"""
root = Node(5)
root.left = Node(4)
root.right = Node(5)
root.left.left = Node(4)
root.left.right = Node(4)
root.right.right = Node(5)
countSingle(root)
print ("Count of Single Valued Subtrees is" , countSingle(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
using System;
// C# program to find count of single valued subtrees
/* Class containing left and right child of current
node and key value*/
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class Count
{
public int count = 0;
}
public class BinaryTree
{
public Node root;
public Count ct = new Count();
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
public virtual bool countSingleRec(Node node, Count c)
{
// Return false to indicate NULL
if (node == null)
{
return true;
}
// Recursively count in left and right subtrees also
bool left = countSingleRec(node.left, c);
bool right = countSingleRec(node.right, c);
// If any of the subtrees is not singly, then this
// cannot be singly.
if (left == false || right == false)
{
return false;
}
// If left subtree is singly and non-empty, but data
// doesn't match
if (node.left != null && node.data != node.left.data)
{
return false;
}
// Same for right subtree
if (node.right != null && node.data != node.right.data)
{
return false;
}
// If none of the above conditions is true, then
// tree rooted under root is single valued, increment
// count and return true.
c.count++;
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
public virtual int countSingle()
{
return countSingle(root);
}
public virtual int countSingle(Node node)
{
// Recursive function to count
countSingleRec(node, ct);
return ct.count;
}
// Driver program to test above functions
public static void Main(string[] args)
{
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
Console.WriteLine("The count of single valued sub trees is : " + tree.countSingle());
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// javascript program to find count of single valued subtrees
/* Class containing left and right child of current
node and key value*/
class Node
{
constructor(item)
{
this.data = item;
this.left = this.right = null;
}
}
class Count
{
constructor(){
this.count = 0;
}
}
var root;
var ct = new Count();
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
function countSingleRec( node, c)
{
// Return false to indicate NULL
if (node == null)
return true;
// Recursively count in left and right subtrees also
var left = countSingleRec(node.left, c);
var right = countSingleRec(node.right, c);
// If any of the subtrees is not singly, then this
// cannot be singly.
if (left == false || right == false)
return false;
// If left subtree is singly and non-empty, but data
// doesn't match
if (node.left != null && node.data != node.left.data)
return false;
// Same for right subtree
if (node.right != null && node.data != node.right.data)
return false;
// If none of the above conditions is true, then
// tree rooted under root is single valued, increment
// count and return true.
c.count++;
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
function countSingle()
{
return countSingle(root);
}
function countSingle( node)
{
// Recursive function to count
countSingleRec(node, ct);
return ct.count;
}
// Driver program to test above functions
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
root = new Node(5);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(4);
root.left.right = new Node(4);
root.right.right = new Node(5);
document.write("The count of single valued sub trees is : "
+ countSingle(root));
// This code contributed by aashish1995
</script>
OutputCount of Single Valued Subtrees is 5
Time complexity of this solution is O(n) where n is number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of the tree due to recursion call.
Approach 2: Breadth First Search:
Here's the overall approach of the algorithm using BFS:
- The algorithm includes a helper method to check if a given node is part of a singly valued subtree. It compares the node's value with its left and right child nodes' values.
- The algorithm initializes the count variable to 0.
- It performs a BFS traversal using a queue. It starts by enqueuing the root node.
- Inside the BFS loop, it dequeues a node and checks if it is singly valued.
- If the current node is singly valued, it increments the count variable.
- The algorithm enqueues the left and right child nodes of the current node, if they exist.
- Once the BFS traversal is complete, the count variable contains the total count of single-valued subtrees.
- The algorithm returns the count of single-valued subtrees.
Here is the code of above approach:
C++
#include <iostream>
#include <queue>
using namespace std;
// Class containing left and right child of current
// node and key value
class Node
{
public:
int data;
Node *left, *right;
Node(int item)
{
data = item;
left = right = NULL;
}
};
class Count
{
public:
int count = 0;
};
class BinaryTree
{
public:
Node *root;
Count ct;
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
bool countSingleRec(Node *node, Count &c)
{
// Return false to indicate NULL
if (node == NULL)
{
return true;
}
// Perform BFS
queue<Node *> q;
q.push(node);
while (!q.empty())
{
Node *curr = q.front();
q.pop();
// Check if the current node is singly valued
if (isSingleValued(curr))
{
c.count++;
}
// Enqueue the left and right child nodes
if (curr->left != NULL)
{
q.push(curr->left);
}
if (curr->right != NULL)
{
q.push(curr->right);
}
}
return true;
}
// Helper function to check if a node is singly valued
bool isSingleValued(Node *node)
{
if (node->left != NULL && node->data != node->left->data)
{
return false;
}
if (node->right != NULL && node->data != node->right->data)
{
return false;
}
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
int countSingle()
{
return countSingle(root);
}
int countSingle(Node *node)
{
// Recursive function to count
countSingleRec(node, ct);
return ct.count;
}
};
// Driver program to test above functions
int main()
{
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
BinaryTree tree;
tree.root = new Node(5);
tree.root->left = new Node(4);
tree.root->right = new Node(5);
tree.root->left->left = new Node(4);
tree.root->left->right = new Node(4);
tree.root->right->right = new Node(5);
cout << "The count of single valued subtrees is: " << tree.countSingle() << endl;
return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
}
class Count {
int count = 0;
}
class BinaryTree {
Node root;
Count ct = new Count();
// This function increments count by number of single valued subtrees under root.
// It returns true if subtree under root is singly valued, else false.
boolean countSingleRec(Node node, Count c) {
if (node == null) {
return true;
}
Queue<Node> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
Node curr = queue.poll();
if (isSingleValued(curr)) {
c.count++;
}
if (curr.left != null) {
queue.add(curr.left);
}
if (curr.right != null) {
queue.add(curr.right);
}
}
return true;
}
// Helper function to check if a node is singly valued
boolean isSingleValued(Node node) {
if (node.left != null && node.data != node.left.data) {
return false;
}
if (node.right != null && node.data != node.right.data) {
return false;
}
return true;
}
// This function mainly calls countSingleRec() after initializing count as 0
int countSingle() {
return countSingleRec(root, ct) ? ct.count : 0;
}
// Driver program to test above functions
public static void main(String[] args) {
// Let us construct the below tree
// 5
// / \
// 4 5
// / \ \
// 4 4 5
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
System.out.println("The count of single valued subtrees is: " + tree.countSingle());
}
}
Python
from collections import deque
class Node:
def __init__(self, item):
self.data = item
self.left = None
self.right = None
class Count:
def __init__(self):
self.count = 0
class BinaryTree:
def __init__(self):
self.root = None
self.ct = Count()
def countSingleRec(self, node, c):
if node is None:
return True
q = deque()
q.append(node)
while q:
curr = q.popleft()
if self.isSingleValued(curr):
c.count += 1
if curr.left:
q.append(curr.left)
if curr.right:
q.append(curr.right)
return True
def isSingleValued(self, node):
if node.left and node.data != node.left.data:
return False
if node.right and node.data != node.right.data:
return False
return True
def countSingle(self):
self.countSingleRec(self.root, self.ct)
return self.ct.count
if __name__ == "__main__":
# Construct the tree
tree = BinaryTree()
tree.root = Node(5)
tree.root.left = Node(4)
tree.root.right = Node(5)
tree.root.left.left = Node(4)
tree.root.left.right = Node(4)
tree.root.right.right = Node(5)
print("The count of single valued subtrees is:", tree.countSingle())
C#
using System;
using System.Collections.Generic;
/* Class containing left and right child of current
node and key value*/
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class Count
{
public int count = 0;
}
public class BinaryTree
{
public Node root;
public Count ct = new Count();
// This function increments count by number of single
// valued subtrees under root. It returns true if subtree
// under root is Singly, else false.
public virtual bool countSingleRec(Node node, Count c)
{
// Return false to indicate NULL
if (node == null)
{
return true;
}
// Perform BFS
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(node);
while (queue.Count > 0)
{
Node curr = queue.Dequeue();
// Check if the current node is singly valued
if (isSingleValued(curr))
{
c.count++;
}
// Enqueue the left and right child nodes
if (curr.left != null)
{
queue.Enqueue(curr.left);
}
if (curr.right != null)
{
queue.Enqueue(curr.right);
}
}
return true;
}
// Helper function to check if a node is singly valued
private bool isSingleValued(Node node)
{
if (node.left != null && node.data != node.left.data)
{
return false;
}
if (node.right != null && node.data != node.right.data)
{
return false;
}
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
public virtual int countSingle()
{
return countSingle(root);
}
public virtual int countSingle(Node node)
{
// Recursive function to count
countSingleRec(node, ct);
return ct.count;
}
// Driver program to test above functions
public static void Main(string[] args)
{
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
Console.WriteLine("The count of single valued subtrees is: " + tree.countSingle());
}
}
JavaScript
class Node {
constructor(item) {
this.data = item;
this.left = this.right = null;
}
}
class Count {
constructor() {
this.count = 0;
}
}
class BinaryTree {
constructor() {
this.root = null;
this.ct = new Count();
}
// This function increments count by the number of single
// valued subtrees under root. It returns true if the subtree
// under root is singly, else false.
countSingleRec(node, c) {
// Return true to indicate null node
if (node === null) {
return true;
}
// Perform BFS
const queue = [];
queue.push(node);
while (queue.length !== 0) {
const curr = queue.shift();
// Check if the current node is singly valued
if (this.isSingleValued(curr)) {
c.count++;
}
// Enqueue the left and right child nodes
if (curr.left !== null) {
queue.push(curr.left);
}
if (curr.right !== null) {
queue.push(curr.right);
}
}
return true;
}
// Helper function to check if a node is singly valued
isSingleValued(node) {
if (node.left !== null && node.data !== node.left.data) {
return false;
}
if (node.right !== null && node.data !== node.right.data) {
return false;
}
return true;
}
// This function mainly calls countSingleRec()
// after initializing count as 0
countSingle() {
return this.countSingle(this.root);
}
countSingle(node) {
// Recursive function to count
this.countSingleRec(node, this.ct);
return this.ct.count;
}
}
// Driver program to test above functions
function main() {
/* Let us construct the below tree
5
/ \
4 5
/ \ \
4 4 5 */
const tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(4);
tree.root.right.right = new Node(5);
console.log("The count of single valued subtrees is:", tree.countSingle());
}
main();
Output
The count of single valued sub trees is : 5
Time complexity: O(n), where n is the number of nodes in given binary tree.
Auxiliary Space: O(h), where h is the height of the tree due to recursion call.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem