43 lines
799 B
Go
43 lines
799 B
Go
package main
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
/**
|
|
* Definition for a binary tree node.
|
|
* type TreeNode struct {
|
|
* Val int
|
|
* Left *TreeNode
|
|
* Right *TreeNode
|
|
* }
|
|
*/
|
|
func minCameraCover(root *TreeNode) int {
|
|
covered := map[*TreeNode]bool{
|
|
nil: true,
|
|
}
|
|
return dfs(root, nil, covered)
|
|
}
|
|
|
|
func dfs(node, parent *TreeNode, covered map[*TreeNode]bool) int {
|
|
if node != nil {
|
|
out := dfs(node.Left, node, covered)
|
|
out += dfs(node.Right, node, covered)
|
|
|
|
_, nc := covered[node]
|
|
_, lc := covered[node.Left]
|
|
_, rc := covered[node.Right]
|
|
if parent == nil && !nc || !lc || !rc {
|
|
covered[node] = true
|
|
covered[parent] = true
|
|
covered[node.Left] = true
|
|
covered[node.Right] = true
|
|
return out + 1
|
|
}
|
|
return out
|
|
}
|
|
return 0
|
|
}
|