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).
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.
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.
Thanks to Gaurav Ahirwar for suggesting above solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count subtrees that sum up to a given value x only using single recursive function
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Number of subtrees having odd count of even numbers
- Count of subtrees in a Binary Tree having XOR value K
- Count of subtrees in a Binary Tree having bitwise OR value K
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Find largest subtree having identical left and right subtrees
- Find All Duplicate Subtrees
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Calculate number of nodes in all subtrees | Using DFS
- Subtrees formed after bursting nodes
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Minimum valued node having maximum depth in an N-ary Tree
- Difference between sum of even and odd valued nodes in a Binary Tree
- Print cousins of a given node in Binary Tree | Single Traversal
- Zig Zag Level order traversal of a tree using single array
- Minimum count of Full Binary Trees such that the count of leaves is N
- Find count of pair of nodes at even distance
- Queries to find the count of shortest paths in a Tree that contains a given edge
- Program to count leaf nodes in a binary tree