A recursive c++ solution


  • 0
    T
    int countUnivalSubtrees(TreeNode* root) {
            if(!root) return 0;
            else if(!root->left&&!root->right) return 1;
            int lnum=countUnivalSubtrees(root->left); //count leftsubtree values
            int rnum=countUnivalSubtrees(root->right); //count rightsubtree values
            bool test=is_unival_tree(root); //test whether the tree itself is univalue tree
            if(test) return lnum+rnum+1;
            else return lnum+rnum;
            
        }
        
    bool is_unival_tree(TreeNode* root){
        if(!root->left&&!root->right) return true;
        bool l=true,leq=true;
        if(root->left){l=is_unival_tree(root->left);leq=(root->val==root->left->val);}
        bool r=true,req=true;
        if(root->right){r=is_unival_tree(root->right);req=(root->val==root->right->val);}
        
        return l&&leq&&r&&req;
    }

Log in to reply
 

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