<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 
{
    #define tn TreeNode* 
    #define inf (1<<20)
    map<pair<tn, pair<bool, bool>>, int> dp; 

    int solve(tn root, bool cam, bool parCam)
    {
        if(root == NULL)
        {
            if(cam) return inf;
            else return 0;
        }

        if(root->left == NULL && root->right == NULL)
        {
            if(cam)
                return 1;
            else
            {
                if(parCam)
                    return 0;
                else return inf;
            }
        }
        
        if(dp.find({root, {cam, parCam}}) != dp.end())
            return dp[{root, {cam, parCam}}];

        if(cam)
        {
            return dp[{root, {cam, parCam}}] = 1 + min(solve(root->left, 0, 1), solve(root->left, 1, 1)) +
                        min(solve(root->right, 0, 1), solve(root->right, 1, 1));
        }
        
        else
        {
            if(parCam)
            {
                return dp[{root, {cam, parCam}}] = min(solve(root->left, 0, 0), solve(root->left, 1, 0)) +
                        min(solve(root->right, 0, 0), solve(root->right, 1, 0));
            }
            else
            {
                int op1 = solve(root->left, 1, 0) + min(solve(root->right, 0, 0), solve(root->right, 1, 0));
                int op2 = solve(root->right, 1, 0) + min(solve(root->left, 0, 0), solve(root->left, 1, 0));
                return dp[{root, {cam, parCam}}] = min(op1, op2);
            }
        }
    }

public:
    int minCameraCover(TreeNode* root) 
    {
        dp.clear();
        return min(solve(root, 0, 0), solve(root, 1, 0));
    }
};
28900