<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p>

<p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p>

<p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg" style="width: 277px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [3,2,3,null,3,null,1]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg" style="width: 357px; height: 293px;" />
<pre>
<strong>Input:</strong> root = [3,4,5,1,3,null,1]
<strong>Output:</strong> 9
<strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9.
</pre>

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

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
</ul>


class Solution
{
	public:
		int rob(TreeNode* root)
		{
			int ans = 0;
			unordered_map<TreeNode*, int> dp_rob, dp_pass;
			
			dp_rob[root] = payDay(root, dp_rob, dp_pass);
			dp_pass[root] = payDay(root->left, dp_rob, dp_pass), payDay(root->right, dp_rob, dp_pass);

			return max(dp_rob[root], dp_pass[root]);
		}

		int payDay(TreeNode* root, unordered_map<TreeNode*, int>& dp_rob, unordered_map<TreeNode*, int>& dp_pass)
		{
			if(root == nullptr) return 0;

			TreeNode* l = root->left;
			TreeNode* r = root->right;
			TreeNode *ll = nullptr, *lr = nullptr;
			TreeNode *rl = nullptr, *rr = nullptr;
			if(l != nullptr)
			{
				ll = l->left;
				lr = l->right;
			}
			if(r != nullptr)
			{
				rl = r->left;
				rr = r->right;
			}

			if(dp_rob.find(root) == dp_rob.end())
				dp_rob[root] = root->val + payDay(ll, dp_rob, dp_pass) + payDay(lr, dp_rob, dp_pass) + 
					payDay(rl, dp_rob, dp_pass) + payDay(rr, dp_rob, dp_pass);
			if(dp_pass.find(root) == dp_pass.end())
				dp_pass[root] = payDay(l, dp_rob, dp_pass) + payDay(r, dp_rob, dp_pass);

			return max(dp_rob[root], dp_pass[root]);
		}
};


26935