250. Count Univalue Subtrees

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4
// This includes duplicate calculation (Preorder Traversal)
int res = 0;
bool isUnival(TreeNode* node, int target) {
    if (!node) return true;
    return node->val == target && isUnival(node->left, target) && isUnival(node->right, target);
}
int countUnivalSubtrees(TreeNode* root) { // time: O(n^2); space: O(n)
    if (!root) return res;
    if (isUnival(root, root->val)) ++res;
    countUnivalSubtrees(root->left);
    countUnivalSubtrees(root->right);
    return res;
}

Last updated

Was this helpful?