Advertisement
nikunjsoni

968

Apr 23rd, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     int ans=0;
  15.     int dfs(TreeNode* curr){
  16.         // 2 -> grandparent
  17.         // 1 -> parent
  18.         // 0 -> child/leaf
  19.         // Place camera only at parent  node only.
  20.        
  21.         if(!curr) return 2;
  22.         int left = dfs(curr->left);
  23.         int right = dfs(curr->right);
  24.         if(left == 0 || right == 0){
  25.             ans++;
  26.             return 1;
  27.         }
  28.         if(left == 1 || right == 1)
  29.             return 2;
  30.         return 0;
  31.     }
  32.    
  33.     int minCameraCover(TreeNode* root) {
  34.         if(dfs(root) == 0) ans++;
  35.         return ans;
  36.     }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement