Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Count Univalue Subtrees

Moderate
0/80
Average time to solve is 30m
profile
Contributed by
85 upvotes
Asked in companies
AmazonInfosysIBM

Problem statement

You are given a binary tree. Return the count of unival sub-trees in the given binary tree. In unival trees, all the nodes, below the root node, have the same value as the data of the root.

For example: for the binary tree, given in the following diagram, the number of unival trees is 5.

alt-text

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer T, the number of test cases.

The next T lines, where each line contains elements in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 on its place.

For example, the input for the tree depicted in the below image would be :

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null (-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 
The sequence will be put together in a single line separated by a single space. Hence, for the above depicted tree, the input will be given as:

1    
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output Format:
For every test case print single line containing an integer i.e the count of unival trees.

Note

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
0 <= N <= 10^5
0 <= data <= 10^4, where data is the value for a node.

Time Limit: 1sec
Sample Input 1:
1 1 1 -1 -1 -1 -1
Sample Output 1:
3
Sample Input 2:
1 2 3 2 -1 3 4 -1 -1 3 3 -1 -1 -1 -1 -1 -1
Sample Output 2:
6
Explanation to Sample Input 2:
The input binary tree will be represented as 

alt-text

In the above diagram, the orange marked nodes are the root nodes of the unival sub-trees for the given binary tree.
Hint

Check for all possible subtrees whether they are unival trees or not.

Approaches (2)
Brute Force

A brute force approach is to traverse all nodes of the tree. For each node, we will calculate the number of unival subtrees recursively from the left and right subtrees of the current node, as count. Now we will check all nodes in the subtree of the current node using the either recursive or iterative method. If all the subnodes have value equals the current node value then we will increment the count.

Time Complexity

O(N^2), where N is the total number of nodes in the given binary tree.
 

In the worst case(given binary tree is a skewed tree), for each node, we will be iterating over all elements in its subtree.

Space Complexity

O(N), where N is the total number of nodes in the given binary tree.
 

In the worst case, the depth of recursion can extend up to O(N). So, extra space will be required for the recursion stack.

Code Solution
(100% EXP penalty)
Count Univalue Subtrees
All tags
Sort by
Search icon

Interview problems

C++ Soln

bool isUni(BinaryTreeNode<int>* root, int &count){
    if(root==NULL) return true;
    bool l = isUni(root->left, count);
    bool r = isUni(root->right, count);
    if(l && r){
        if(root->left != NULL && root->data != root->left->data ||
        root->right != NULL && root->data != root->right->data){
            return false;
        }
        count++;
        return true;
    }
    else return false;
}
int countUnivalTrees(BinaryTreeNode<int> *root)
{
    int count = 0;
    isUni(root, count);
    return count;
    
}
18 views
0 replies
0 upvotes

Interview problems

C++ | dfs - recursive | EASY

//Step 1: Understand problem

//we want to check first if a subtree is Univalue or not

//Finding such univalue subtree and counting total no of nodes

//in all such uni subtrees gives our answer

 

//Step2: Algorithm

//we use DFS to traverse to leaf nodes, basically

//for every sub/root we want to check that if that subtree

//is Uni or not.

 

//At every instace, basically we will have the left child and right

//child of that sub root, then only we proceed to IF Statments

 

//if both l and r TRUE, meaning we good till l subtree and r subtree

//and just wanna check for the root of l n r

 

bool isUni(BinaryTreeNode<int>* root, int &count){

    if(root==NULL) return true;

    bool l = isUni(root->left, count);

    bool r = isUni(root->right, count);

    if(l && r){

        if(root->left != NULL && root->data != root->left->data ||

        root->right != NULL && root->data != root->right->data){

            return false;

        }

        count++;

        return true;

    }

    else return false;

}

int countUnivalTrees(BinaryTreeNode<int> *root)

{

    int count = 0;

    isUni(root, count);

    return count;

    

}

77 views
0 replies
0 upvotes

Interview problems

Count Univalue Subtrees

void inorder(BinaryTreeNode<int> *root, int &c)

{

    if(root==NULL)

    return ;

    inorder(root->left,c);

    inorder(root->right,c);

    if(root->left==NULL && root->right==NULL)

    c++;

    else

    {

        if(root->left!=NULL && root->right!=NULL && root->data==root->left->data && root->data==root->right->data)

        c++;

        else if(root->left!=NULL && root->right==NULL && root->data==root->left->data)

        c++;

        else if(root->right!=NULL && root->left==NULL && root->data==root->right->data)

        c++;

        else

        root->data=-1;

 

    }

}

int countUnivalTrees(BinaryTreeNode<int> *root)

{

    int c=0;

    inorder(root,c);

    return c;

}

212 views
0 replies
2 upvotes

Interview problems

Python Solution

count = 0

def helper(node):
    global count
    if node is None:
        return (-1, True)
    l = helper(node.left)
    r = helper(node.right)
    if l[0] == r[0] == -1:
        count += 1
        return (node.data, True)
    else:
        if l[1] and r[1]:
            if l[0] == -1 or r[0] == -1:
                if l[0] == node.data:
                    count += 1
                    return (node.data, True)
                elif r[0] == node.data:
                    count += 1
                    return (node.data, True)
            if l[0] == r[0] == node.data:
                count += 1
                return (node.data, True)
    return (node.data, False)
    
    

    

def countUnivalTrees(root):
    # Write your code here.
    # This function returns the updated root.
    if root is None:
        return 0
    global count
    helper(root)
    ans = count
    count = 0
    return ans
53 views
0 replies
0 upvotes

Interview problems

C++ Solution Accepted

/*************************************************************
 
    Following is the Binary Tree node structure

    class BinaryTreeNode 
    {
    public : 
        T data;
        BinaryTreeNode<T> *left;
        BinaryTreeNode<T> *right;

        BinaryTreeNode(T data) {
            this -> data = data;
            left = NULL;
            right = NULL;
        }
    };

*************************************************************/

int ans;

int countUnique(BinaryTreeNode<int> *root)
{

    if(root->left == nullptr and root->right == nullptr)
    {
        ++ans;  // Every leaf node is a unique value subtree
        return root->data;
    }

    int leftVal = -2, rightVal = -2;

    if(root->left)
        leftVal = countUnique(root->left);

    if(root->right)
        rightVal = countUnique(root->right);

    if(leftVal == rightVal and leftVal != -1)
    {
        if(leftVal == root->data)
        {
            ++ans;
            return leftVal;
        }

        return -1;
    }

    else if(leftVal == -2 and rightVal > 0)
    {
        if(rightVal == root->data)
        {
            ++ans;
            return rightVal;
        }

        return -1;
    }

    else if(rightVal == -2 and leftVal > 0)
    {
        if(leftVal == root->data)
        {
            ++ans;
            return leftVal;
        }
        
        return -1;
    }

    return -1;
}

int countUnivalTrees(BinaryTreeNode<int> *root)
{
    // for every subtree we will return the total number
    // of unique values that it contains

    ans = 0;

    if(root == nullptr)
    return 0;

    if(root->left == nullptr and root->right == nullptr)
    return 1;

    int val = 0;

    int count = countUnique(root);

    return ans;

}
161 views
0 replies
0 upvotes

Interview problems

easy to understand cpp solution

#include <bits/stdc++.h>

/*************************************************************
 
    Following is the Binary Tree node structure

    class BinaryTreeNode 
    {
    public : 
        T data;
        BinaryTreeNode<T> *left;
        BinaryTreeNode<T> *right;

        BinaryTreeNode(T data) {
            this -> data = data;
            left = NULL;
            right = NULL;
        }
    };

*************************************************************/

array<int,2> helper(BinaryTreeNode<int> *root){
    if (root == nullptr){
        return {0, true};
    }

    if (!root->left && !root->right){
        return {1, true};
    }

    array<int,2> left = helper(root->left);
    array<int,2> right = helper(root->right);


    int count = left[0] + right[0];
    bool isUnival = left[1] && right[1];
    
    if (root->left){
        if (root->left->data != root->data){
            isUnival = false;
        }
    }

    if (root->right){
        if (root->right->data != root->data){
            isUnival = false;
        }
    }

    if (isUnival) count++;

    return {count, isUnival};
}

int countUnivalTrees(BinaryTreeNode<int> *root)
{
    auto ans = helper(root);
    return ans[0];
}
142 views
0 replies
0 upvotes

Interview problems

C++ || Easy to understand

bool recursion(BinaryTreeNode<int> *root, int &cnt){

    if(root == NULL){

        return true;

    }

 

    bool left = recursion(root->left, cnt);

    bool right = recursion(root->right, cnt);

    if(left && right){

        if ((root->left != nullptr && root->data != root->left->data) ||

            (root->right != nullptr && root->data != root->right->data)) {

                return false;

        }

        cnt++;

        return true;

    }

    return false;

}

int countUnivalTrees(BinaryTreeNode<int> *root)

{

    int cnt = 0;

    recursion(root, cnt);

    return cnt;

}

188 views
0 replies
2 upvotes

Interview problems

Java O(N) Solution

/*    Time Complexity: O(N)    Space Complexity: O(N)        Where N is the total number of nodes in the given Binary Tree.   */

public class Solution {

public static int countUnivalTrees(BinaryTreeNode<Integer> root) {  return countHelper(root).count; } public static Pair countHelper(BinaryTreeNode<Integer> root) {  if(root == null) {   return new Pair(0, true);  }    Pair left = countHelper(root.left);  Pair right = countHelper(root.right);    int totalCount = left.count + right.count;  boolean isUnival = false;  Pair ans = new Pair(totalCount, isUnival);

 if(left.isUnival && right.isUnival) {   if(root.right != null && !root.data.equals(root.right.data)) {    return ans;   }   if(root.left != null && !root.data.equals(root.left.data)) {    return ans;   }      ans.count++;   ans.isUnival = true;   return ans;  }    return ans; } }

class Pair { int count; boolean isUnival; Pair(int count, boolean isUnival) {  this.count = count;  this.isUnival = isUnival; } }  

java

140 views
0 replies
1 upvote

Interview problems

Easy solution in cpp

/*************************************************************
 
    Following is the Binary Tree node structure

    class BinaryTreeNode 
    {
    public : 
        T data;
        BinaryTreeNode<T> *left;
        BinaryTreeNode<T> *right;

        BinaryTreeNode(T data) {
            this -> data = data;
            left = NULL;
            right = NULL;
        }
    };

*************************************************************/
#include<bits/stdc++.h>
int ans;
unordered_set<int> solve(BinaryTreeNode<int> *root)
{
    if(root==NULL)
    return {};
    if(root->left==NULL and root->right==NULL)
    {
        ans++;
        unordered_set<int>s;
        s.insert(root->data);
        return s;
    }
    unordered_set<int>l= solve(root->left);
    unordered_set<int>r= solve(root->right);
    unordered_set<int>s;
    s.insert(root->data);
    for(auto x:l)
    s.insert(x);
    for(auto x:r)
    s.insert(x);
    if(s.size()==1)
    ans++;
    return s;
}
int countUnivalTrees(BinaryTreeNode<int> *root)
{
    // Write your code here.
    if(root==NULL)
    return 0;
    ans=0;
    solve(root);
    return ans;
}
107 views
0 replies
0 upvotes

Interview problems

I done all correct and all sample test cases are running but after submitting it, only one test case run. Can anyone explain me this please?


bool Count(BinaryTreeNode<int>* root, int &count){

    if(root==NULL){

        return true;

    }

    bool l =Count(root->left, count);

    bool r =Count(root->right, count);

    if( l && r ){

        if( (root->left==NULL && root->right==NULL) || (root->left==NULL && root->data == root->right->data) || (root->right == NULL && root->data == root->left->data) || (root->data == root->left->data && root->data == root->right->data)){

            count++;

            return true;

        }

    }

    return false;

}

int countUnivalTrees(BinaryTreeNode<int> *root)

{

    // Write your code here.

    if(root==NULL){

        return 0;

    }

    int count=0;

    Count(root,count);

 

    return count;

}
186 views
1 reply
0 upvotes
Full screen
Console