Count Univalue Subtrees Posted on 2018-11-01 Descriptionhttps://leetcode.com/problems/count-univalue-subtrees/ Description1234567891011121314151617181920212223242526272829303132333435/** * 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 {public: int countUnivalSubtrees(TreeNode* root) { int count = 0; if (root == NULL) return 0; helper(count, root); return count; } int helper(int& count, TreeNode* root) { int leftValue = (root->left) ? helper(count, root->left) : INT_MIN; int rightValue = (root->right) ? helper(count, root->right) : INT_MIN; if (leftValue == INT_MAX || rightValue == INT_MAX) return INT_MAX; if ( (leftValue == INT_MIN || root->val == leftValue) && (rightValue == INT_MIN || root->val == rightValue) ) { count += 1; return root->val; } //Failed return INT_MAX; }};