VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-count-of-singly-subtrees/

⇱ Find Count of Single Valued Subtrees - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

[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).


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.


Output
The count of Single Valued Subtrees is 5

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

Comment
Article Tags:
Article Tags: