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。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*使用深度优先搜索,从叶节点开始遍历。深度优先搜索函数参数为根节点,返回值一个枚举类,分别是camera(该节点有相机),covered(该节点没有相机但被覆盖),None(该节点没有相机也没有被覆盖)。先判断该节点的两个子节点是否有None状态,如果有,则该节点为camera,相机数+1;再判断该节点的子节点是否有camera状态,如果有,则该节点状态为covered,否则该节点为None状态。对于空节点,返回covered状态。如果根节点返回None状态,则相机数需+1;
*/
class Solution {
public:
int minCameraCover(TreeNode* root) {
State r_state = dfs(root);
if(r_state == None)
{
ans++;
}
return ans;
}
private:
enum State{ None,Covered,Camera};
int ans = 0;
State dfs(TreeNode* root)
{
if(!root) return Covered;
State lc = dfs(root->left);
State rc = dfs(root->right);
if(lc == None || rc == None)
{
ans++;
return Camera;
}
if(lc == Camera || rc == Camera)
{
return Covered;
}
return None;
}
};