LeetCode968. Binary Tree Cameras

文章目录

一、题目

You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

Return the minimum number of cameras needed to monitor all nodes of the tree.

Example 1:

Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:

Input: root = [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.

Constraints:

The number of nodes in the tree is in the range [1, 1000].
Node.val == 0

二、题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
   
public:
    int res = 0;
    /*
        三种状态
        0-无覆盖
        1-有摄像头
        2-有覆盖
    */
    int traversal(TreeNode* cur){
   
        //空节点:默认有覆盖
        if(cur == nullptr) return 2;
        int left = traversal(cur->left);
        int right = traversal(cur->right);
        //左右节点均有覆盖
        if(left == 2 && right == 2) return 0;
        //左节点无覆盖或右节点无覆盖
        if(left == 0 || right == 0){
   
            res++;
            return 1;
        }
        //左右节点中至少一个有摄像头
        if(left == 1 || right == 1) return 2;
        return -1;
    }
    int minCameraCover(TreeNode* root) {
   
        //如果根节点无覆盖
        if(traversal(root) == 0) res++;
        return res;
    }
};

相关推荐

  1. LeetCode968. Binary Tree Cameras

    2023-12-10 14:38:02       48 阅读
  2. LeetCode 968.监控二叉树 (hard)

    2023-12-10 14:38:02       49 阅读
  3. LeetCode965. Univalued Binary Tree

    2023-12-10 14:38:02       52 阅读
  4. LeetCode938. Range Sum of BST

    2023-12-10 14:38:02       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-10 14:38:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-10 14:38:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-10 14:38:02       87 阅读
  4. Python语言-面向对象

    2023-12-10 14:38:02       96 阅读

热门阅读

  1. 力扣44题通配符匹配题解

    2023-12-10 14:38:02       58 阅读
  2. vue内置组件

    2023-12-10 14:38:02       53 阅读
  3. 【贪心算法】 Opponents

    2023-12-10 14:38:02       54 阅读
  4. 3.2 Puppet 和 Chef 的比较与应用

    2023-12-10 14:38:02       42 阅读
  5. Django大回顾 - 9 Auth模块的使用、缓存

    2023-12-10 14:38:02       54 阅读
  6. tomcat安全基线检查

    2023-12-10 14:38:02       55 阅读
  7. 单例模式【C#】

    2023-12-10 14:38:02       54 阅读