Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 ans=0;
- int dfs(TreeNode* curr){
- // 2 -> grandparent
- // 1 -> parent
- // 0 -> child/leaf
- // Place camera only at parent node only.
- if(!curr) return 2;
- int left = dfs(curr->left);
- int right = dfs(curr->right);
- if(left == 0 || right == 0){
- ans++;
- return 1;
- }
- if(left == 1 || right == 1)
- return 2;
- return 0;
- }
- int minCameraCover(TreeNode* root) {
- if(dfs(root) == 0) ans++;
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement