website/content/ChapterFour/0900~0999/0968.Binary-Tree-Cameras.md
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:
[1, 1000].给定一个二叉树,我们在树的节点上安装摄像头。节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。计算监控树的所有节点所需的最小摄像头数量。
提示:
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type status int
const (
isLeaf status = iota
parentofLeaf
isMonitoredWithoutCamera
)
func minCameraCover(root *TreeNode) int {
res := 0
if minCameraCoverDFS(root, &res) == isLeaf {
res++
}
return res
}
func minCameraCoverDFS(root *TreeNode, res *int) status {
if root == nil {
return 2
}
left, right := minCameraCoverDFS(root.Left, res), minCameraCoverDFS(root.Right, res)
if left == isLeaf || right == isLeaf {
*res++
return parentofLeaf
} else if left == parentofLeaf || right == parentofLeaf {
return isMonitoredWithoutCamera
} else {
return isLeaf
}
}