Univalue Tree Count - Amazon Top Interview Questions

Problem Statement :

A univalue tree is a tree where all nodes under it have the same value.

Given a binary tree root, return the number of univalue subtrees.


1 ≤ n ≤ 100,000 where n is the number of nodes in root

Example 1


root = [0, [1, null, null], [0, [1, [1, null, null], [1, null, null]], [0, null, null]]]




The unival trees include four leaf nodes (three of them are 1s, the other one is the rightmost 0), and one subtree in the middle (containing all 1s).

Example 2


root = [1, [0, null, null], [0, null, null]]




The two leaf nodes are unival trees.

Solution :


                        Solution in C++ :

bool dfs(Tree* node, int& cnt) {
    if (node == NULL) {
        return true;
    bool ls = dfs(node->left, cnt);
    bool rs = dfs(node->right, cnt);
    int left_value = (node->left != NULL ? node->left->val : node->val);
    int right_value = (node->right != NULL ? node->right->val : node->val);
    if (node->val == left_value && node->val == right_value && ls && rs) {
        return true;
    return false;
int solve(Tree* root) {
    int cnt = 0;
    dfs(root, cnt);
    return cnt;

                        Solution in Java :

import java.util.*;

 * public class Tree {
 *   int val;
 *   Tree left;
 *   Tree right;
 * }
class Solution {
    class Node {
        int num;
        boolean isUnivalued;
        public Node(int n, boolean isUnivalued) {
            this.num = n;
            this.isUnivalued = isUnivalued;
    int count = 0;

    public int solve(Tree root) {
        return count;

    private Node dfs(Tree node) {
        if (node == null)
            return null;
        if (node.left == null && node.right == null) {
            return new Node(node.val, true);

        boolean isUnivalued = true;
        if (node.left != null) {
            Node left = dfs(node.left);
            isUnivalued = (isUnivalued && left.isUnivalued && node.val == left.num);
        if (node.right != null) {
            Node right = dfs(node.right);
            isUnivalued = (isUnivalued && right.isUnivalued && node.val == right.num);
        if (isUnivalued)
        return new Node(node.val, isUnivalued);

                        Solution in Python : 
class Solution:
    def solve(self, root):
        self.cnt = 0

        def rec(node):
            if not node:
                return True
            left = not node.left or (node.left.val == node.val)
            right = not node.right or (node.right.val == node.val)
            left_sub = rec(node.left)
            right_sub = rec(node.right)
            if left and right and left_sub and right_sub:
                self.cnt += 1
                return True
            return False

        return self.cnt

View More Similar Problems

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →