Binary Tree Cameras Problem
Description
LeetCode Problem 968.
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.
Example 1:
1
2
3
Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
1
2
3
Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: 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.
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- Node.val == 0
Sample C++ Code
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
/**
* 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 {
public:
#define NO_CAMERA 0
#define HAS_CAMERA 2
#define NOT_NEEDED 1
int ans = 0;
int dfs(TreeNode *root) {
if (!root) return NOT_NEEDED;
int l = dfs(root->left);
int r = dfs(root->right);
if (l == NO_CAMERA || r == NO_CAMERA) {
ans++;
return HAS_CAMERA;
} else if (l == HAS_CAMERA || r == HAS_CAMERA) {
return NOT_NEEDED;
} else {
return NO_CAMERA;
}
}
int minCameraCover(TreeNode* root) {
if (dfs(root) == NO_CAMERA) ans++;
return ans;
}
};