[LeetCode] Binary Tree Cameras

968. Binary Tree Cameras

You are given the root 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.

Return the minimum number of cameras needed to monitor all nodes of the tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<TreeNode*, int> dp[2][2];
int helper(TreeNode* node, bool watch, bool pWatch) {
if(!node) return 0;
if(dp[watch][pWatch].count(node)) return dp[watch][pWatch][node];
int& res = dp[watch][pWatch][node] = helper(node->left, true, true) + helper(node->right, true, true) + 1;
if(watch) {
res = min(res, helper(node->left, false, true) + helper(node->right, false, true));
} else if(!watch and pWatch) {
if(node->left and node->right) {
res = min(res, helper(node->left, false, false) + helper(node->right, false, true));
res = min(res, helper(node->right, false, false) + helper(node->left, false, true));
} else if(node->left) {
res = min(res, helper(node->left, false, false));
} else if(node->right) {
res = min(res, helper(node->right, false, false));
}
}
return res;
}
public:
int minCameraCover(TreeNode* root) {
return helper(root, false, true);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/10/PS/LeetCode/binary-tree-cameras/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.