C++ 7 lines solution


  • 0
    L
    class Solution {
    public:
        int countUnivalSubtrees(TreeNode* root) {
            bool u = true;
            return isUni(root, u);
        }
        
        int isUni(TreeNode *root, bool &u) {
            if (!root) return 0;
            bool a = true, b = true;
            int res = isUni(root->left, a) + isUni(root->right, b);
            u = a && b && (root->left?root->val == root->left->val:true) && (root->right?root->val == root->right->val:true);
            return res + u;
        }
    };

Log in to reply
 

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