leetcode968监控二叉树

leetcode 968 Binary Tree Cameras

Posted by BY on September 22, 2020

前言

持续更新了

正文

问题来源

本问题来自leetcode上的968题。

问题描述

给定一个二叉树,我们在树的节点上安装摄像头。
节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。
计算监控树的所有节点所需的最小摄像头数量。

示例 1:

输入:[0,0,null,0,0]
输出:1
解释:如图所示,一台摄像头足以监控所有节点。

示例 2:

输入:[0,0,null,0,null,0,null,null,0]
输出:2
解释:需要至少两个摄像头来监视树的所有节点。 上图显示了摄像头放置的有效位置之一。

分析:

``` /**

  • Definition for a binary tree node.
  • type TreeNode struct {
  • Val int
  • Left *TreeNode
  • Right *TreeNode
  • } */ const inf = math.MaxInt32 / 2 // 或 math.MaxInt64 / 2

func minCameraCover(root TreeNode) int { var dfs func(TreeNode) (a, b, c int) dfs = func(node *TreeNode) (a, b, c int) { if node == nil { return inf, 0, 0 } la, lb, lc := dfs(node.Left) ra, rb, rc := dfs(node.Right) a = lc + rc + 1 b = min(a, min(la+rb, ra+lb)) c = min(a, lb+rb) return } _, ans, _ := dfs(root) return ans }

func min(a, b int) int { if a < b { return a } return b }```

总结:

勤思考。

结语

不管怎么样好好加油。