A recursive c++ solution

  • 0
    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;
        bool r=true,req=true;
        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.