Description
Submission
/**
* 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 {
int ret;
public:
int countUnivalSubtrees(TreeNode* root) {
if(!root) return 0;
return countUnivalSubtrees(root->left) + countUnivalSubtrees(root->right) + isUnivalSubtree(root, root->val);
}
// ret: {uni-value til now, value_of_leaf}
bool isUnivalSubtree(TreeNode* root, int val) {
if(!root) return true;
if(root->val != val) return false;
return isUnivalSubtree(root->left, val) && isUnivalSubtree(root->right, val);
}
};