11-line C++ solution


  • 0
    F

    isValid: decide whether a tree is a Univalue Subtree
    valid Univalue Subtree:

    1. single node
    2. two child is either empty or is also a valid Univalue Subtree AND equal to root value
    class Solution {
    public:
        int countUnivalSubtrees(TreeNode* root) {
            if(!root) return 0;
            return countUnivalSubtrees(root->left) + countUnivalSubtrees(root->right) + isValid(root);
        }
        
        bool isValid(TreeNode* root)
        {
            if(!root || (root && !root->left && !root->right)) return true;
            if((!root->left || (isValid(root->left) && root->val==root->left->val)) &&
                (!root->right || (isValid(root->right) && root->val==root->right->val))
            )return true;
            return false;
        }
    };
    

Log in to reply
 

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