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++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
Node* newNode( int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
bool countSingleRec(Node* root, int &count)
{
if (root == NULL)
return true ;
bool left = countSingleRec(root->left, count);
bool right = countSingleRec(root->right, count);
if (left == false || right == false )
return false ;
if (root->left && root->data != root->left->data)
return false ;
if (root->right && root->data != root->right->data)
return false ;
count++;
return true ;
}
int countSingle(Node* root)
{
int count = 0;
countSingleRec(root, count);
return count;
}
int main()
{
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
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();
boolean countSingleRec(Node node, Count c)
{
if (node == null )
return true ;
boolean left = countSingleRec(node.left, c);
boolean right = countSingleRec(node.right, c);
if (left == false || right == false )
return false ;
if (node.left != null && node.data != node.left.data)
return false ;
if (node.right != null && node.data != node.right.data)
return false ;
c.count++;
return true ;
}
int countSingle()
{
return countSingle(root);
}
int countSingle(Node node)
{
countSingleRec(node, ct);
return ct.count;
}
public static void main(String args[])
{
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());
}
}
|
Python3
class Node:
def __init__( self ,data):
self .data = data
self .left = None
self .right = None
def countSingleRec(root , count):
if root is None :
return True
left = countSingleRec(root.left , count)
right = countSingleRec(root.right , count)
if left = = False or right = = False :
return False
if root.left and root.data ! = root.left.data:
return False
if root.right and root.data ! = root.right.data:
return False
count[ 0 ] + = 1
return True
def countSingle(root):
count = [ 0 ]
countSingleRec(root , count)
return count[ 0 ]
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))
|
C#
using System;
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();
public virtual bool countSingleRec(Node node, Count c)
{
if (node == null )
{
return true ;
}
bool left = countSingleRec(node.left, c);
bool right = countSingleRec(node.right, c);
if (left == false || right == false )
{
return false ;
}
if (node.left != null && node.data != node.left.data)
{
return false ;
}
if (node.right != null && node.data != node.right.data)
{
return false ;
}
c.count++;
return true ;
}
public virtual int countSingle()
{
return countSingle(root);
}
public virtual int countSingle(Node node)
{
countSingleRec(node, ct);
return ct.count;
}
public static void Main( string [] args)
{
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());
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .data = item;
this .left = this .right = null ;
}
}
class Count
{
constructor(){
this .count = 0;
}
}
var root;
var ct = new Count();
function countSingleRec( node, c)
{
if (node == null )
return true ;
var left = countSingleRec(node.left, c);
var right = countSingleRec(node.right, c);
if (left == false || right == false )
return false ;
if (node.left != null && node.data != node.left.data)
return false ;
if (node.right != null && node.data != node.right.data)
return false ;
c.count++;
return true ;
}
function countSingle()
{
return countSingle(root);
}
function countSingle( node)
{
countSingleRec(node, ct);
return ct.count;
}
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));
</script>
|
Output
Count 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 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;
bool countSingleRec(Node *node, Count &c)
{
if (node == NULL)
{
return true ;
}
queue<Node *> q;
q.push(node);
while (!q.empty())
{
Node *curr = q.front();
q.pop();
if (isSingleValued(curr))
{
c.count++;
}
if (curr->left != NULL)
{
q.push(curr->left);
}
if (curr->right != NULL)
{
q.push(curr->right);
}
}
return true ;
}
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 ;
}
int countSingle()
{
return countSingle(root);
}
int countSingle(Node *node)
{
countSingleRec(node, ct);
return ct.count;
}
};
int main()
{
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();
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 ;
}
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 ;
}
int countSingle() {
return countSingleRec(root, ct) ? ct.count : 0 ;
}
public static void main(String[] args) {
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__" :
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;
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();
public virtual bool countSingleRec(Node node, Count c)
{
if (node == null )
{
return true ;
}
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(node);
while (queue.Count > 0)
{
Node curr = queue.Dequeue();
if (isSingleValued(curr))
{
c.count++;
}
if (curr.left != null )
{
queue.Enqueue(curr.left);
}
if (curr.right != null )
{
queue.Enqueue(curr.right);
}
}
return true ;
}
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 ;
}
public virtual int countSingle()
{
return countSingle(root);
}
public virtual int countSingle(Node node)
{
countSingleRec(node, ct);
return ct.count;
}
public static void Main( string [] args)
{
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();
}
countSingleRec(node, c) {
if (node === null ) {
return true ;
}
const queue = [];
queue.push(node);
while (queue.length !== 0) {
const curr = queue.shift();
if ( this .isSingleValued(curr)) {
c.count++;
}
if (curr.left !== null ) {
queue.push(curr.left);
}
if (curr.right !== null ) {
queue.push(curr.right);
}
}
return true ;
}
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 ;
}
countSingle() {
return this .countSingle( this .root);
}
countSingle(node) {
this .countSingleRec(node, this .ct);
return this .ct.count;
}
}
function main() {
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!