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
} };