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