My simple c++ solution


  • 1
    K
    class Solution {
    public:
    int countUnivalSubtrees(TreeNode* root) {
        int count=0;
        helper(root, count);
        return count;
    }
    void helper(TreeNode * root, int & count){
        if(!root)return;
        if(sameValue(root, root->val))count++;
        helper(root->left, count);
        helper(root->right, count);
    }
    bool sameValue(TreeNode * root, int value){
        if(!root)return true;
        else if(root->val!=value)return false;
        else return sameValue(root->left, value) && sameValue(root->right, value);
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.