Given a binary tree, we install cameras on the nodes of the tree. node
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:this
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:spa
[1, 1000]
.
作了好久,仍是写不出来,看了网上的答案。确实很精妙。利用了返回值表达了三种状态,利用引用存储最后结果。code
还有一点就是在放相机的时候,在递归函数里,父节点必定比节点有优点,能放父节点必定放父节点,拿叶节点来blog
举例,此时若是放叶节点,能影响到的点只有它自己和父节点,而父节点能影响到子节点,自己,和它的父节点。递归
因此这是一个贪心算法。input
class Solution { public: int minCameraCover(TreeNode* root) { int sum=0; if(dfs(root,sum)==0) sum++;// if root is not monitored, we place an additional camera here
return sum; } int dfs(TreeNode * tr, int& sum){ if(!tr) return 1; int l=dfs(tr->left,sum), r=dfs(tr->right,sum); if(l==0||r==0){// if at least 1 child is not monitored, we need to place a camera at current node
sum++; return 2; }else if(l==2||r==2){// if at least 1 child has camera, the current node if monitored. Thus, we don't need to place a camera here
return 1; }else{// 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;// this return statement won't be triggered
} };