leetcode 968. 监控二叉树
程序员文章站
2022-05-20 10:34:32
...
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minCameraCover(TreeNode* root, int& result)
{
if (root == NULL)
{
return 1; // 空节点都设置为被覆盖,可以使叶子节点设置为2,根据父节点情况决定是否被覆盖
}
int left = minCameraCover(root->left, result);
int right = minCameraCover(root->right, result);
// cout << "left: " << left << " right: " << right << endl;
if (left == 1 && right == 1)
{
return 2;
}
if (left == 2 || right == 2)
{
result++;
return 0;
}
if (left == 0 || right == 0)
{
return 1;
}
return -1;
}
int minCameraCover(TreeNode* root) {
// 节点有3种状态,装监控,被覆盖,没被覆盖 分别设置为0, 1, 2,没被扫描的设置为-1
// 从下往上扫描,叶子节点不加监控,扫描到叶子节点直接设置为2
// 当前节点存在3中情况 1. 叶子节点有监控,当前节点被覆盖 2. 叶子节点有一个没被覆盖,当前节点装监控 3. 当前节点叶子节点都被覆盖,当前节点置为没被覆盖,先不决定装不装监控
int result = 0;
if (root == NULL)
{
return result;
}
int ret = minCameraCover(root, result);
// cout << "ret: " << ret << endl;
if (ret == 2)
{
result = result + 1;
}
return result;
}
};
上一篇: 03-树2 List Leaves(25 分)/C
下一篇: Eclipse断点调试
推荐阅读
-
Leetcode算法【114. 二叉树展开为链表】
-
二叉树(LeetCode) C++相关知识代码 系列1
-
荐 八十一、Python | Leetcode 二叉树系列(下篇)
-
C++实现LeetCode(105.由先序和中序遍历建立二叉树)
-
C++实现LeetCode(889.由先序和后序遍历建立二叉树)
-
C++实现LeetCode(106.由中序和后序遍历建立二叉树)
-
leetcode 面试题32 (剑指offer)- II. 从上到下打印二叉树 II(python3)
-
leetcode 113 剑指offer 面试题34. 二叉树中和为某一值的路径(python3)
-
leetcode 面试题32 - III. 从上到下打印二叉树 III(python3)
-
LeetCode第958题 二叉树的完全性检验