KatInterview

250. Count Univalue Subtrees

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of "uni-value subtrees" in a given binary tree. A uni-value subtree is defined as a subtree where all of its nodes have the same value. A single node (like a leaf) is also considered a subtree and, by definition, is always a uni-value subtree.

Solution

Count Univalue Subtrees in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
        self.count = 0
        self.is_unival(root)
        return self.count

    def is_unival(self, node: Optional[TreeNode]) -> bool:
        # Base case: an empty tree is considered a univalue subtree.
        if not node:
            return True
        
        # Recursively check left and right subtrees (post-order traversal).
        left_is_unival = self.is_unival(node.left)
        right_is_unival = self.is_unival(node.right)
        
        # If both children form univalue subtrees, we then check if the current
        # node can form a univalue subtree with them.
        if left_is_unival and right_is_unival:
            # Check if left child exists and its value matches the current node's value.
            if node.left and node.left.val != node.val:
                return False
            # Check if right child exists and its value matches the current node's value.
            if node.right and node.right.val != node.val:
                return False
            
            # If all checks pass, this node is the root of a univalue subtree.
            self.count += 1
            return True
            
        # If either of the children does not form a univalue subtree,
        # then the subtree rooted at the current node cannot be one.
        return False

Count Univalue Subtrees in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int count = 0;

    public int countUnivalSubtrees(TreeNode root) {
        isUnival(root);
        return count;
    }

    private boolean isUnival(TreeNode node) {
        // Base case: an empty tree is considered a univalue subtree.
        if (node == null) {
            return true;
        }

        // Recursively check left and right subtrees (post-order traversal).
        boolean leftIsUnival = isUnival(node.left);
        boolean rightIsUnival = isUnival(node.right);

        // If both children form univalue subtrees, we then check if the current
        // node can form a univalue subtree with them.
        if (leftIsUnival && rightIsUnival) {
            // Check if left child exists and its value matches the current node's value.
            if (node.left != null && node.left.val != node.val) {
                return false;
            }
            // Check if right child exists and its value matches the current node's value.
            if (node.right != null && node.right.val != node.val) {
                return false;
            }
            
            // If all checks pass, this node is the root of a univalue subtree.
            count++;
            return true;
        }
        
        // If either of the children does not form a univalue subtree,
        // then the subtree rooted at the current node cannot be one.
        return false;
    }
}

Count Univalue Subtrees in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        isUnival(root);
        return count;
    }

private:
    int count = 0;

    bool isUnival(TreeNode* node) {
        // Base case: an empty tree is considered a univalue subtree.
        if (node == nullptr) {
            return true;
        }

        // Recursively check left and right subtrees (post-order traversal).
        bool leftIsUnival = isUnival(node->left);
        bool rightIsUnival = isUnival(node->right);

        // If both children form univalue subtrees, we then check if the current
        // node can form a univalue subtree with them.
        if (leftIsUnival && rightIsUnival) {
            // Check if left child exists and its value matches the current node's value.
            if (node->left != nullptr && node->left->val != node->val) {
                return false;
            }
            // Check if right child exists and its value matches the current node's value.
            if (node->right != nullptr && node->right->val != node->val) {
                return false;
            }

            // If all checks pass, this node is the root of a univalue subtree.
            count++;
            return true;
        }
        
        // If either of the children does not form a univalue subtree,
        // then the subtree rooted at the current node cannot be one.
        return false;
    }
};

Count Univalue Subtrees in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function countUnivalSubtrees(root: TreeNode | null): number {
    let count = 0;

    function isUnival(node: TreeNode | null): boolean {
        // Base case: an empty tree is considered a univalue subtree.
        if (node === null) {
            return true;
        }

        // Recursively check left and right subtrees (post-order traversal).
        const leftIsUnival = isUnival(node.left);
        const rightIsUnival = isUnival(node.right);

        // If both children form univalue subtrees, we then check if the current
        // node can form a univalue subtree with them.
        if (leftIsUnival && rightIsUnival) {
            // Check if left child exists and its value matches the current node's value.
            if (node.left !== null && node.left.val !== node.val) {
                return false;
            }
            // Check if right child exists and its value matches the current node's value.
            if (node.right !== null && node.right.val !== node.val) {
                return false;
            }
            
            // If all checks pass, this node is the root of a univalue subtree.
            count++;
            return true;
        }
        
        // If either of the children does not form a univalue subtree,
        // then the subtree rooted at the current node cannot be one.
        return false;
    }
    
    isUnival(root);
    return count;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.