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).
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.
classSolution {
publicintcountUnivalSubtrees(TreeNode root) {
if (root ==null) {
return 0;
}
int ans = countUnivalTreeBad(root.left) + countUnivalTreeBad(root.right);
if (isUnivalTree(root)) {
ans += 1;
}
return ans;
}
privatebooleanisUnivalTree(TreeNode root) {
if (root ==null) {
returntrue;
}
boolean left = isUnivalTree(root.left);
boolean right = isUnivalTree(root.right);
// If any of the subtrees is not singly, then this// cannot be singly.if (!left ||!right) {
returnfalse;
}
// If left subtree is singly and non-empty, but data doesn't matchif (root.left!=null&& root.val!= root.left.val) {
returnfalse;
}
// Same for right subtreeif (root.right!=null&& root.val!= root.right.val) {
returnfalse;
}
returntrue;
}
}
⏰ Time complexity: O(n^2). The time complexity on each step is O(n) for isUnival and we call it every time we traverse, so the time complexity is On(n^2).
🧺 Space complexity: O(n)
Method 2 - Check Unival and Return counter in 1 call#
We can calculate the count and check if the subtrees are univalue trees together.
One way to do is to return array of object and return both together. Other ways is to use Wrapper class in java. We wrap the counter integer in Counter class.
classSolution {
privateint ans;
publicintcountUnivalSubtrees(TreeNode root) {
dfs(root);
return ans;
}
// This function increments counter ans by number of single// valued subtrees under root. It returns true if subtree// under root is Singly, else false.booleandfs(TreeNode root) {
// Return false to indicate NULLif (root ==null) {
returntrue;
}
// Recursively count in left and right subtrees alsoboolean left = dfs(root.left);
boolean right = dfs(root.right);
// If any of the subtrees is not singly, then this// cannot be singly.if (!left ||!right) {
returnfalse;
}
// If left subtree is singly and non-empty, but data// doesn't matchif (root.left!=null&& root.val!= root.left.val) {
returnfalse;
}
// Same for right subtreeif (root.right!=null&& root.val!= root.right.val) {
returnfalse;
}
// If none of the above conditions is true, then// tree rooted under root is single valued, increment// count and return true. ans++;
returntrue;
}
}