968. Binary Tree Cameras
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: [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.
Note:
- The number of nodes in the given tree will be in the range [1, 1000].
- Every node has value 0.
方法1: greedy + dynamic programming
思路:
用greedy的做法,能把责任往上推就往上推,因为parent可以照顾到更多的节点。We put camera at as higher level (closer to root) as possible. We use post-order DFS here. The return value of DFS() has following meanings. 0: there is no camera at this node, and it’s not monitored by camera at either of its children, which means neither of child nodes has camera. 1: there is no camera at this node; however, this node is monitored by at least 1 of its children, which means at least 1 of its children has camera. 2: there is a camera at this node.
Complexity
Time complexity: O(n)
Space complexity: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minCameraCover(TreeNode* root) {
int sum = 0;
if (camHelper(root, sum) == 0) sum++; // if root is not monitored, we place an additional camera here
return sum;
}
int camHelper(TreeNode* root, int & sum) {
if (!root) return 1;
int left = camHelper(root -> left, sum);
int right = camHelper(root -> right, sum);
if (left == 0 || right == 0) { // if at least 1 child is not monitored, we need to place a camera at current node
sum++;
return 2;
}
else if (left == 1 && right == 1) { // if both children are monitored but have no camera, we don't need to place a camera here. We place the camera at its parent node at the higher level.
return 0;
}
return 1; // if at least 1 child has camera, the current node is monitored. Thus, we don't need to place a camera here
}
};