C++ one-pass solution for Count Univalue Subtree


  • 0
    G
    class Solution {
    public:
        // int result;
        int countUnivalSubtrees(TreeNode* root) {
            if(root==NULL)return 0;
            int result=0;
            check(root,result);
            return result;
            
        }
        
        bool check(TreeNode*root,int &result){
            // if(root==NULL)return true;
            if(root->left==NULL&&root->right==NULL) {result++;return true;}
            bool status=true;
            if(root->left!=NULL){
                if(root->left->val!=root->val) status=false;
                status=check(root->left,result)&&status;
            }
            if(root->right!=NULL){
                if(root->right->val!=root->val)status=false;
                status=check(root->right,result)&&status;
            }
            result= (status==true? result+1:result);
            return status;
        }
    };

Log in to reply
 

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