leetcode 968. Binary Tree Cameras

968. Binary Tree Camerashtml

思路:若是子節點只能覆蓋到父節點、當前節點,可是父節點能夠覆蓋到他的父節點、子節點、當前節點,因此從葉子節點往上考慮node

0表明子節點沒有被覆蓋spa

1表明子節點被覆蓋,可是子節點沒有cameracode

2表明子節點被覆蓋,子節點有camerahtm

http://www.javashuo.com/article/p-sbxbnfhk-ek.htmlblog

/**
 * 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;
    }
};
相關文章
相關標籤/搜索