My C++ Solution - Easy to understand!!!


  • 2
    E
    class Solution {
    public:
        int countUnivalSubtrees(TreeNode* root) {
            if(root == NULL) {
                return result;
            }
            if(same(root, root -> val)) {
                ++result;
            }
            countUnivalSubtrees(root -> left);
            countUnivalSubtrees(root -> right);
            return result;
        }
    private:
        int result = 0;
        bool same(TreeNode* root, int val) {
            if(root == NULL) {
                return true;
            }
            return root -> val == val && same(root -> left, val) && same(root -> right, val);
        }
    };

Log in to reply
 

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