Find Count of Single Valued Subtrees

Last Updated : 3 Feb, 2026

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. All leaves are considered as single valued subtrees.

Example: 

Input: root of below tree

420851418

Output: 4
There are 4 subtrees with single values.

Input: root of below tree

420851419

Output: 5
There are five subtrees with single values.

Try It Yourself
redirect icon

[Naive Approach] Top-Down Traversal

A simple solution involves traversing the tree. For each node, check if all values within its subtree are identical; if so, increment the count. This approach has a time complexity of O(n^2).

C++
#include <iostream>
#include <queue>
using namespace std;

// Tree Node Structure
class Node {
public:
    int data;
    Node *left, *right;
    Node(int item) {
        data = item;
        left = right = NULL;
    }
};

// Deep-check: Verifies if EVERY node in the subtree matches 'val'
bool isUnivalue(Node* node, int val) {
    if (node == NULL) return true;
    if (node->data != val) return false;
    return isUnivalue(node->left, val) && isUnivalue(node->right, val);
}

int countSingle(Node* root) {
    if (root == NULL) return 0;
    int count = 0;
    queue<Node*> q;
    q.push(root);

    // BFS Traversal: Visit every node in the tree
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();

        // Independent Audit: Check the entire subtree of the current node
        if (isUnivalue(curr, curr->data)) {
            count++;
        }

        if (curr->left) q.push(curr->left);
        if (curr->right) q.push(curr->right);
    }
    return count;
}

int main() {
    
    /* Constructing the specific tree:
              5
             / \
            4   5
           / \   \
          4   4   5
    */
    Node* tree = new Node(5);
    tree->left = new Node(4);
    tree->right = new Node(5);
    
    tree->left->left = new Node(4);
    tree->left->right = new Node(4);
    
    tree->right->right = new Node(5);

    cout << "The count of single valued subtrees is: " << countSingle(tree) << endl;

    return 0;
}
Java
import java.util.*;

// Tree Node Structure
class Node {
    public int data;
    public Node left, right;

    public Node(int item) {
        data = item;
        left = right = null;
    }
}

public class GFG {
    // Deep-check: Verifies if EVERY node in the subtree matches 'val'
    public static boolean isUnivalue(Node node, int val) {
        if (node == null) return true;
        if (node.data!= val) return false;
        return isUnivalue(node.left, val) && isUnivalue(node.right, val);
    }

    public static int countSingle(Node root) {
        if (root == null) return 0;
        int count = 0;
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        // BFS Traversal: Visit every node in the tree
        while (!q.isEmpty()) {
            Node curr = q.poll();

            // Independent Audit: Check the entire subtree of the current node
            if (isUnivalue(curr, curr.data)) {
                count++;
            }

            if (curr.left!= null) q.add(curr.left);
            if (curr.right!= null) q.add(curr.right);
        }
        return count;
    }

    public static void main(String[] args) {
        /* Constructing the specific tree:
               5
              / \
             4   5
            / \   \
           4   4   5
        */
        Node tree = new Node(5);
        tree.left = new Node(4);
        tree.right = new Node(5);
        
        tree.left.left = new Node(4);
        tree.left.right = new Node(4);
        
        tree.right.right = new Node(5);

        System.out.println("The count of single valued subtrees is: " + countSingle(tree));
    }
}
Python
from collections import deque

# Tree Node Structure
class Node:
    def __init__(self, item):
        self.data = item
        self.left = self.right = None

# Deep-check: Verifies if EVERY node in the subtree matches 'val'
def is_univalue(node, val):
    if node is None:
        return True
    if node.data!= val:
        return False
    return is_univalue(node.left, val) and is_univalue(node.right, val)

def count_single(root):
    if root is None:
        return 0
    count = 0
    q = deque([root])

    # BFS Traversal: Visit every node in the tree
    while q:
        curr = q.popleft()

        # Independent Audit: Check the entire subtree of the current node
        if is_univalue(curr, curr.data):
            count += 1

        if curr.left:
            q.append(curr.left)
        if curr.right:
            q.append(curr.right)
    return count

if __name__ == '__main__':
    # Constructing the specific tree:
    #        5
    #       / \
    #      4   5
    #     / \   \
    #    4   4   5
    tree = Node(5)
    tree.left = Node(4)
    tree.right = Node(5)
    
    tree.left.left = Node(4)
    tree.left.right = Node(4)
    
    tree.right.right = Node(5)

    print('The count of single valued subtrees is:', count_single(tree))
C#
using System;
using System.Collections.Generic;

// Tree Node Structure
public class Node {
    public int data;
    public Node left, right;

    public Node(int item) {
        data = item;
        left = right = null;
    }
}

public class GFG {
    // Deep-check: Verifies if EVERY node in the subtree matches 'val'
    public static bool IsUnivalue(Node node, int val) {
        if (node == null) return true;
        if (node.data!= val) return false;
        return IsUnivalue(node.left, val) && IsUnivalue(node.right, val);
    }

    public static int CountSingle(Node root) {
        if (root == null) return 0;
        int count = 0;
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        // BFS Traversal: Visit every node in the tree
        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // Independent Audit: Check the entire subtree of the current node
            if (IsUnivalue(curr, curr.data)) {
                count++;
            }

            if (curr.left!= null) q.Enqueue(curr.left);
            if (curr.right!= null) q.Enqueue(curr.right);
        }
        return count;
    }

    public static void Main() {
        /* Constructing the specific tree:
               5
              / \
             4   5
            / \   \
           4   4   5
        */
        Node tree = new Node(5);
        tree.left = new Node(4);
        tree.right = new Node(5);
        
        tree.left.left = new Node(4);
        tree.left.right = new Node(4);
        
        tree.right.right = new Node(5);

        Console.WriteLine("The count of single valued subtrees is: " + CountSingle(tree));
    }
}
JavaScript
// Tree Node Structure
class Node {
    constructor(item) {
        this.data = item;
        this.left = this.right = null;
    }
}

// Deep-check: Verifies if EVERY node in the subtree matches 'val'
function isUnivalue(node, val) {
    if (node === null) return true;
    if (node.data!== val) return false;
    return isUnivalue(node.left, val) && isUnivalue(node.right, val);
}

function countSingle(root) {
    if (root === null) return 0;
    let count = 0;
    let q = [root];

    // BFS Traversal: Visit every node in the tree
    while (q.length > 0) {
        let curr = q.shift();

        // Independent Audit: Check the entire subtree of the current node
        if (isUnivalue(curr, curr.data)) {
            count++;
        }

        if (curr.left!== null) q.push(curr.left);
        if (curr.right!== null) q.push(curr.right);
    }
    return count;
}

// Constructing the specific tree:
//        5
//       / \
//      4   5
//     / \   \
//    4   4   5
let tree = new Node(5);
tree.left = new Node(4);
tree.right = new Node(5);

tree.left.left = new Node(4);
tree.left.right = new Node(4);

tree.right.right = new Node(5);

console.log('The count of single valued subtrees is:', countSingle(tree));

Output
The count of single valued subtrees is: 5

Time complexity: O(n^2)
Auxiliary Space: O(log(n))

[Expected Approach] Bottom-Up Traversal

An efficient solution traverses the tree in a bottom-up manner. For each visited subtree, return true if the subtree rooted there is single-valued, and increment the count. The key is to use the count as a reference parameter in recursive calls and use the returned values to determine if the left and right subtrees are single-valued.

C++
#include <iostream>
using namespace std;

// Tree Node Structure
struct Node
{
    int data;
    struct Node* left, *right;
    Node(int val){
        data=val;
        left=right=NULL;
    }
};

/* 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        = 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);

    cout << "The count of Single Valued Subtrees is "
         << countSingle(root);
    return 0;
}
Java
import java.util.*;

// Tree Node Structure
class Node {
    int data;
    Node left, right;
    Node(int val) {
        data = val;
        left = right = null;
    }
}

public class GFG {
    /* This function increments count by number of single 
       valued subtrees under root. It returns true if subtree 
       under root is Singly, else false. */
    static boolean countSingleRec(Node root, int[] count) {
        // Return true to indicate NULL
        if (root == null)
           return true;

        // Recursively count in left and right subtrees also
        boolean left = countSingleRec(root.left, count);
        boolean right = countSingleRec(root.right, count);

        /* If any of the subtrees is not singly, then this
           cannot be singly. */
        if (!left ||!right)
           return false;

        /* If left subtree is singly and non-empty, but data
           doesn't match */
        if (root.left!= null && root.data!= root.left.data)
            return false;

        // Same for right subtree
        if (root.right!= null && 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]++;
        return true;
    }

    /* This function mainly calls countSingleRec()
       after initializing count as 0 */
    static int countSingle(Node root) {
        // Initialize result
        int[] count = {0};

        // Recursive function to count
        countSingleRec(root, count);

        return count[0];
    }

    public static void main(String[] args) {
        /* Let us construct the below tree
                 5
               /  \
              4    5
             / \    \
            4   4    5 */
        Node 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);

        System.out.println("The count of Single Valued Subtrees is " +
                           countSingle(root));
    }
}
Python
import collections

# Tree Node Structure
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


def countSingleRec(root, count):
    # Return true to indicate NULL
    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 not left or not right:
        return False

    # If left subtree is singly and non-empty, but data
    # doesn't match
    if root.left is not None and root.data!= root.left.data:
        return False

    # Same for right subtree
    if root.right is not None 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


def countSingle(root):
    # Initialize result
    count = [0]

    # Recursive function to count
    countSingleRec(root, count)

    return count[0]


if __name__ == '__main__':
    # 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)

    print("The count of Single Valued Subtrees is ", countSingle(root))
C#
using System;

// Tree Node Structure
public class Node
{
    public int data;
    public Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

public class GFG
{
    // Recursive function to count single valued subtrees
    private static bool CountSingleRec(Node root, ref 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, ref count);
        bool right = CountSingleRec(root.right, ref count);

        // If any of the subtrees is not singly, then this
        // cannot be singly.
        if (!left ||!right)
            return false;

        // If left subtree is singly and non-empty, but data
        // doesn't match
        if (root.left!= null && root.data!= root.left.data)
            return false;

        // Same for right subtree
        if (root.right!= null && 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 += 1;
        return true;
    }

    // Function to count single valued subtrees
    public static int CountSingle(Node root)
    {
        // Initialize result
        int count = 0;

        // Recursive function to count
        CountSingleRec(root, ref count);

        return count;
    }

    public static void Main()
    {
        // Let us construct the below tree
        //       5
        //     /  \
        //    4    5
        //   / \    \
        //  4   4    5
        Node 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);

        Console.WriteLine("The count of Single Valued Subtrees is " + CountSingle(root));
    }
}
JavaScript
/* Tree Node Structure */
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function countSingleRec(root, count) {
    // Return true to indicate NULL
    if (root === null) {
        return true;
    }

    // Recursively count in left and right subtrees also
    let left = countSingleRec(root.left, count);
    let right = countSingleRec(root.right, count);

    // If any of the subtrees is not singly, then this
    // cannot be singly.
    if (!left ||!right) {
        return false;
    }

    // If left subtree is singly and non-empty, but data
    // doesn't match
    if (root.left!== null && root.data!== root.left.data) {
        return false;
    }

    // Same for right subtree
    if (root.right!== null && 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;
}

function countSingle(root) {
    // Initialize result
    let count = [0];

    // Recursive function to count
    countSingleRec(root, count);

    return count[0];
}

if (typeof require!== 'undefined' && require.main === module) {
    // Let us construct the below tree
    //       5
    //     /  \
    //    4    5
    //   / \    \
    //  4   4    5
    let 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);

    console.log('The count of Single Valued Subtrees is ' + countSingle(root));
}

Output
The count of Single Valued Subtrees is 5

Time complexity: O(n)
Auxiliary Space: O(h)

Comment