LeetCode968. 监控二叉树
1. 问题描述
2. 思路
3. 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minCameraCover(root *TreeNode) int {
var result int
temp := traversal(root, &result)
if temp == 0 {
result++
}
return result
}
// 0: 未覆盖
// 1: 节点安装了监视器
// 2: 有覆盖
func traversal(root *TreeNode, result *int) int {
if root == nil {
return 2
}
left := traversal(root.Left, result)
right := traversal(root.Right, result)
// 情况1:左右节点都有覆盖
if left == 2 && right == 2 {
return 0
}
// 情况2:左右节点有一个未覆盖
if left == 0 || right == 0 {
*result++
return 1
}
// 情况3:左右节点有一个安装摄像头
if left == 1 || right == 1 {
return 2
}
return -1
}