4ms C++ solution


  • 0
    Y
    class Solution {
    public:
        int cnt = 0;
        bool allSame(TreeNode* root) {
            bool lht = true, rht = true;
            if (!root) return true;
            if (root->left) lht = allSame(root->left) && (root->left->val == root->val);
            if (root->right) rht = allSame(root->right) && (root->right->val == root->val);
            if (lht && rht) { cnt++; return true; }
            return false;
        }
    
        int countUnivalSubtrees(TreeNode* root) {
            if (!root) return false;
            allSame(root);
            return cnt;
        }
    };

  • 0
    S
    This post is deleted!

Log in to reply
 

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