Leetcode 250 Solution

This article provides solution to leetcode question 250 (count-univalue-subtrees)

https://leetcode.com/problems/count-univalue-subtrees

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int res = 0;

public:
    bool doCountUnivalSubtrees(TreeNode* root)
    {
        if (root == NULL)
            return true;

        bool left_uni_value = doCountUnivalSubtrees(root->left);
        bool right_uni_value = doCountUnivalSubtrees(root->right);

        if (left_uni_value == false || right_uni_value == false)
            return false;

        if (root->left && root->val != root->left->val)
            return false;

        if (root->right && root->val != root->right->val)
            return false;

        res++;
        return true;
    }

    int countUnivalSubtrees(TreeNode* root) {
        res = 0;
        doCountUnivalSubtrees(root);
        return res;
    }
};