leetcode 968. Binary Tree Cameras

968. Binary Tree Cameras

思路:如果子节点只能覆盖到父节点、当前节点,但是父节点可以覆盖到他的父节点、子节点、当前节点,所以从叶子节点往上考虑

0代表子节点没有被覆盖

1代表子节点被覆盖,但是子节点没有camera

2代表子节点被覆盖,子节点有camera

https://www.cnblogs.com/ethanhong/p/10200550.html

/**
 * 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 sum = 0;
        if(minCameraCover(root,sum) == 0)
            sum++;
        return sum;
    }
    int minCameraCover(TreeNode* root,int& sum){
        if(!root)
            return 1;
        int left = minCameraCover(root->left,sum);
        int right = minCameraCover(root->right,sum);
        if(left == 0 || right == 0){
            sum++;
            return 2;
        }
        else if(left == 2 || right == 2)
            return 1;
        else
            return 0;
    }
};

 

posted @ 2019-08-06 20:36  有梦就要去实现他  阅读(617)  评论(0编辑  收藏  举报