<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>

#ifdef LOCAL
  #include "../../lib/bits.h"
  #include "../../lib/leetcode.h"
  #include "../../lib/debug.h"

  using leetcode::TreeNode;
#else
  #define debug(...) 1
#endif

using ll = long long;

class Solution {
public:
  int solve1(TreeNode* root) {
    const int inf = 1e9;

    // none, covered, camera
    const auto& dfs = [&](auto& dfs, TreeNode* current) -> array<ll, 3> {
      if (current->left && current->right) {
        const auto l = dfs(dfs, current->left);
        const auto r = dfs(dfs, current->right);

        return {
          l[1] + r[1],
          min(l[2] + min(r[1], r[2]), r[2] + min(l[1], l[2])),
          min({l[0], l[1], l[2]}) + min({r[0], r[1], r[2]}) + 1
        };
      } else if (current->left) {
        const auto l = dfs(dfs, current->left);
        return { l[1], l[2], min({l[0], l[1], l[2]}) + 1 };
      } else if (current->right) {
        const auto r = dfs(dfs, current->right);
        return { r[1], r[2], min({r[0], r[1], r[2]}) + 1 };
      } else {
        return { 0, inf, 1 };
      }
    };

    const auto ans = dfs(dfs, root);
    return min(ans[1], ans[2]);
  }

  int minCameraCover(TreeNode* root) {
    return solve1(root);
  }
};

// =============================
// https://leetcode.com/problems/binary-tree-cameras/description


#ifdef LOCAL

int main(int argc, char *argv[]) {
  std::ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);

  using namespace leetcode;

  auto root = read_tree();
  const auto result = (new Solution())->minCameraCover(root);
  debug(result);

  return 0;
}

#endif
21600