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
Output: 4 There are 4 subtrees with single values.
Input: root of below tree
Output: 5 There are five subtrees with single values.
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>usingnamespacestd;// Tree Node StructureclassNode{public:intdata;Node*left,*right;Node(intitem){data=item;left=right=NULL;}};// Deep-check: Verifies if EVERY node in the subtree matches 'val'boolisUnivalue(Node*node,intval){if(node==NULL)returntrue;if(node->data!=val)returnfalse;returnisUnivalue(node->left,val)&&isUnivalue(node->right,val);}intcountSingle(Node*root){if(root==NULL)return0;intcount=0;queue<Node*>q;q.push(root);// BFS Traversal: Visit every node in the treewhile(!q.empty()){Node*curr=q.front();q.pop();// Independent Audit: Check the entire subtree of the current nodeif(isUnivalue(curr,curr->data)){count++;}if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}returncount;}intmain(){/* Constructing the specific tree: 5 / \ 4 5 / \ \ 4 4 5 */Node*tree=newNode(5);tree->left=newNode(4);tree->right=newNode(5);tree->left->left=newNode(4);tree->left->right=newNode(4);tree->right->right=newNode(5);cout<<"The count of single valued subtrees is: "<<countSingle(tree)<<endl;return0;}
Java
importjava.util.*;// Tree Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassGFG{// Deep-check: Verifies if EVERY node in the subtree matches 'val'publicstaticbooleanisUnivalue(Nodenode,intval){if(node==null)returntrue;if(node.data!=val)returnfalse;returnisUnivalue(node.left,val)&&isUnivalue(node.right,val);}publicstaticintcountSingle(Noderoot){if(root==null)return0;intcount=0;Queue<Node>q=newLinkedList<>();q.add(root);// BFS Traversal: Visit every node in the treewhile(!q.isEmpty()){Nodecurr=q.poll();// Independent Audit: Check the entire subtree of the current nodeif(isUnivalue(curr,curr.data)){count++;}if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}returncount;}publicstaticvoidmain(String[]args){/* Constructing the specific tree: 5 / \ 4 5 / \ \ 4 4 5 */Nodetree=newNode(5);tree.left=newNode(4);tree.right=newNode(5);tree.left.left=newNode(4);tree.left.right=newNode(4);tree.right.right=newNode(5);System.out.println("The count of single valued subtrees is: "+countSingle(tree));}}
Python
fromcollectionsimportdeque# Tree Node StructureclassNode:def__init__(self,item):self.data=itemself.left=self.right=None# Deep-check: Verifies if EVERY node in the subtree matches 'val'defis_univalue(node,val):ifnodeisNone:returnTrueifnode.data!=val:returnFalsereturnis_univalue(node.left,val)andis_univalue(node.right,val)defcount_single(root):ifrootisNone:return0count=0q=deque([root])# BFS Traversal: Visit every node in the treewhileq:curr=q.popleft()# Independent Audit: Check the entire subtree of the current nodeifis_univalue(curr,curr.data):count+=1ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)returncountif__name__=='__main__':# Constructing the specific tree:# 5# / \# 4 5# / \ \# 4 4 5tree=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#
usingSystem;usingSystem.Collections.Generic;// Tree Node StructurepublicclassNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassGFG{// Deep-check: Verifies if EVERY node in the subtree matches 'val'publicstaticboolIsUnivalue(Nodenode,intval){if(node==null)returntrue;if(node.data!=val)returnfalse;returnIsUnivalue(node.left,val)&&IsUnivalue(node.right,val);}publicstaticintCountSingle(Noderoot){if(root==null)return0;intcount=0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);// BFS Traversal: Visit every node in the treewhile(q.Count>0){Nodecurr=q.Dequeue();// Independent Audit: Check the entire subtree of the current nodeif(IsUnivalue(curr,curr.data)){count++;}if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}returncount;}publicstaticvoidMain(){/* Constructing the specific tree: 5 / \ 4 5 / \ \ 4 4 5 */Nodetree=newNode(5);tree.left=newNode(4);tree.right=newNode(5);tree.left.left=newNode(4);tree.left.right=newNode(4);tree.right.right=newNode(5);Console.WriteLine("The count of single valued subtrees is: "+CountSingle(tree));}}
JavaScript
// Tree Node StructureclassNode{constructor(item){this.data=item;this.left=this.right=null;}}// Deep-check: Verifies if EVERY node in the subtree matches 'val'functionisUnivalue(node,val){if(node===null)returntrue;if(node.data!==val)returnfalse;returnisUnivalue(node.left,val)&&isUnivalue(node.right,val);}functioncountSingle(root){if(root===null)return0;letcount=0;letq=[root];// BFS Traversal: Visit every node in the treewhile(q.length>0){letcurr=q.shift();// Independent Audit: Check the entire subtree of the current nodeif(isUnivalue(curr,curr.data)){count++;}if(curr.left!==null)q.push(curr.left);if(curr.right!==null)q.push(curr.right);}returncount;}// Constructing the specific tree:// 5// / \// 4 5// / \ \// 4 4 5lettree=newNode(5);tree.left=newNode(4);tree.right=newNode(5);tree.left.left=newNode(4);tree.left.right=newNode(4);tree.right.right=newNode(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>usingnamespacestd;// Tree Node StructurestructNode{intdata;structNode*left,*right;Node(intval){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. */boolcountSingleRec(Node*root,int&count){// Return true to indicate NULLif(root==NULL)returntrue;// Recursively count in left and right subtrees alsoboolleft=countSingleRec(root->left,count);boolright=countSingleRec(root->right,count);/* If any of the subtrees is not singly, then this cannot be singly. */if(left==false||right==false)returnfalse;/* If left subtree is singly and non-empty, but data doesn't match */if(root->left&&root->data!=root->left->data)returnfalse;// Same for right subtreeif(root->right&&root->data!=root->right->data)returnfalse;/* If none of the above conditions is true, then tree rooted under root is single valued, increment count and return true. */count++;returntrue;}/* This function mainly calls countSingleRec() after initializing count as 0 */intcountSingle(Node*root){// Initialize resultintcount=0;// Recursive function to countcountSingleRec(root,count);returncount;}// Driver program to testintmain(){/* Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5 */Node*root=newNode(5);root->left=newNode(4);root->right=newNode(5);root->left->left=newNode(4);root->left->right=newNode(4);root->right->right=newNode(5);cout<<"The count of Single Valued Subtrees is "<<countSingle(root);return0;}
Java
importjava.util.*;// Tree Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{/* This function increments count by number of single valued subtrees under root. It returns true if subtree under root is Singly, else false. */staticbooleancountSingleRec(Noderoot,int[]count){// Return true to indicate NULLif(root==null)returntrue;// Recursively count in left and right subtrees alsobooleanleft=countSingleRec(root.left,count);booleanright=countSingleRec(root.right,count);/* 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 match */if(root.left!=null&&root.data!=root.left.data)returnfalse;// Same for right subtreeif(root.right!=null&&root.data!=root.right.data)returnfalse;/* If none of the above conditions is true, then tree rooted under root is single valued, increment count and return true. */count[0]++;returntrue;}/* This function mainly calls countSingleRec() after initializing count as 0 */staticintcountSingle(Noderoot){// Initialize resultint[]count={0};// Recursive function to countcountSingleRec(root,count);returncount[0];}publicstaticvoidmain(String[]args){/* Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5 */Noderoot=newNode(5);root.left=newNode(4);root.right=newNode(5);root.left.left=newNode(4);root.left.right=newNode(4);root.right.right=newNode(5);System.out.println("The count of Single Valued Subtrees is "+countSingle(root));}}
Python
importcollections# Tree Node StructureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefcountSingleRec(root,count):# Return true to indicate NULLifrootisNone:returnTrue# Recursively count in left and right subtrees alsoleft=countSingleRec(root.left,count)right=countSingleRec(root.right,count)# If any of the subtrees is not singly, then this# cannot be singly.ifnotleftornotright:returnFalse# If left subtree is singly and non-empty, but data# doesn't matchifroot.leftisnotNoneandroot.data!=root.left.data:returnFalse# Same for right subtreeifroot.rightisnotNoneandroot.data!=root.right.data:returnFalse# If none of the above conditions is true, then# tree rooted under root is single valued, increment# count and return true.count[0]+=1returnTruedefcountSingle(root):# Initialize resultcount=[0]# Recursive function to countcountSingleRec(root,count)returncount[0]if__name__=='__main__':# Let us construct the below tree# 5# / \# 4 5# / \ \# 4 4 5root=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#
usingSystem;// Tree Node StructurepublicclassNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassGFG{// Recursive function to count single valued subtreesprivatestaticboolCountSingleRec(Noderoot,refintcount){// Return true to indicate NULLif(root==null)returntrue;// Recursively count in left and right subtrees alsoboolleft=CountSingleRec(root.left,refcount);boolright=CountSingleRec(root.right,refcount);// 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.data!=root.left.data)returnfalse;// Same for right subtreeif(root.right!=null&&root.data!=root.right.data)returnfalse;// If none of the above conditions is true, then// tree rooted under root is single valued, increment// count and return true.count+=1;returntrue;}// Function to count single valued subtreespublicstaticintCountSingle(Noderoot){// Initialize resultintcount=0;// Recursive function to countCountSingleRec(root,refcount);returncount;}publicstaticvoidMain(){// Let us construct the below tree// 5// / \// 4 5// / \ \// 4 4 5Noderoot=newNode(5);root.left=newNode(4);root.right=newNode(5);root.left.left=newNode(4);root.left.right=newNode(4);root.right.right=newNode(5);Console.WriteLine("The count of Single Valued Subtrees is "+CountSingle(root));}}
JavaScript
/* Tree Node Structure */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functioncountSingleRec(root,count){// Return true to indicate NULLif(root===null){returntrue;}// Recursively count in left and right subtrees alsoletleft=countSingleRec(root.left,count);letright=countSingleRec(root.right,count);// 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.data!==root.left.data){returnfalse;}// Same for right subtreeif(root.right!==null&&root.data!==root.right.data){returnfalse;}// If none of the above conditions is true, then// tree rooted under root is single valued, increment// count and return true.count[0]+=1;returntrue;}functioncountSingle(root){// Initialize resultletcount=[0];// Recursive function to countcountSingleRec(root,count);returncount[0];}if(typeofrequire!=='undefined'&&require.main===module){// Let us construct the below tree// 5// / \// 4 5// / \ \// 4 4 5letroot=newNode(5);root.left=newNode(4);root.right=newNode(5);root.left.left=newNode(4);root.left.right=newNode(4);root.right.right=newNode(5);console.log('The count of Single Valued Subtrees is '+countSingle(root));}