c++ recursive solution easy to understand


  • 0
    Q
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int countUnivalSubtrees(TreeNode* root) {
            if(root == nullptr)
                return 0;
            if(!root->left && !root->right)
                return 1;
            int res = 0;
            if(isuni(root->left, root->val) && isuni(root->right,root->val))
                res += 1;
            res += countUnivalSubtrees(root->left) + countUnivalSubtrees(root->right);
            
            return res;
        }
        
        bool isuni(TreeNode *root,int cur){
            if(root == nullptr)
                return true;
            
            if(root->val == cur)
                return isuni(root->left, cur) && isuni(root->right,cur);
            else
                return false;
        }
    };
    

Log in to reply
 

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