leetcode 968. Binary Tree Cameras

968. Binary Tree Cameras

Idea: If the child node to the parent node can only cover the current node, but the parent node can cover his parent, the child node, the current node, so consider from leaf nodes up

0 representing the child node is not covered

1 representing the child node to be covered, but no child nodes camera

2 representing the child node is covered with a child node 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;
    }
};

 

Guess you like

Origin www.cnblogs.com/ymjyqsx/p/11311678.html