<p>You are given the <code>root</code> of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.</p>

<p>Return <em>the minimum number of cameras needed to monitor all nodes of the tree</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" style="width: 138px; height: 163px;" />
<pre>
<strong>Input:</strong> root = [0,0,null,0,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> One camera is enough to monitor all nodes if placed as shown.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" style="width: 139px; height: 312px;" />
<pre>
<strong>Input:</strong> root = [0,0,null,0,null,0,null,null,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong> At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
	<li><code>Node.val == 0</code></li>
</ul>

class Solution {
public:
    unordered_map<TreeNode*, int> dp[2][2];
    int solve(TreeNode* curr, bool isMonitored, int isMandatory) {
        // put camera
        if (curr == NULL)
            return isMandatory ? 1e9 : 0;

        if (dp[isMonitored][isMandatory].count(curr) != 0)
            return dp[isMonitored][isMandatory][curr];

        int ans = 1 + solve(curr->left, true, false) +
                  solve(curr->right, true, false);

        if (!isMandatory) {
            // don't put camera
            if (isMonitored) {
                ans = min(ans, solve(curr->left, false, false) +
                                   solve(curr->right, false, false));
            } else {
                int l = solve(curr->left, false, true) +
                        solve(curr->right, false, false);
                int r = solve(curr->right, false, true) +
                        solve(curr->left, false, false);
                ans = min({l, r, ans});
            }
        }
        return dp[isMonitored][isMandatory][curr] = ans;
    }
    int minCameraCover(TreeNode* root) {
        cin.tie(NULL);
        ios_base::sync_with_stdio(false);

        return solve(root, false, false);
    }
};
27500