c++ solution


  • 0
    B
    class Solution {
    public:
        int result=0;
        
        bool unitree(TreeNode *root){
            if(!root->left && !root->right) return true;
            
            if(!root->left) return root->right->val==root->val && unitree(root->right);
            if(!root->right) return root->left->val==root->val && unitree(root->left);
            
            return root->right->val==root->val && unitree(root->right) && root->left->val==root->val && unitree(root->left);
        }
        
        void dfs(TreeNode *root){
            if(!root) return;
            
            if(unitree(root)) result++;
            
            dfs(root->left);
            dfs(root->right);
            
            return ;
        }
        
        int countUnivalSubtrees(TreeNode* root) {
            if(!root) return 0;
            
            dfs(root);
            
            return result;
        }
    };
    

Log in to reply
 

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