Clean c++ dfs solution

  • 0

    helper function returns whether current node is compatible with parent.

    int countUnivalSubtrees(TreeNode* root) {
        int result = 0;
        countUnivalSubtrees(root, 0, result);
        return result;
    bool countUnivalSubtrees(TreeNode *root, int parent, int &result) {
        if (root == NULL)
            return true;
        bool leftUnival = countUnivalSubtrees(root->left, root->val, result);
        bool rightUnival = countUnivalSubtrees(root->right, root->val, result);
        if (leftUnival && rightUnival)
        return leftUnival && rightUnival && root->val == parent;

Log in to reply

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