Fork me on GitHub

Count Univalue Subtrees

Description

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

Description

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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;
}
};