-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathBinary Tree Cameras.cpp
55 lines (39 loc) · 1.37 KB
/
Binary Tree Cameras.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Solution by Rahul Surana
***********************************************************
You are given the root of a binary tree. We install cameras on the tree nodes
where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
***********************************************************
*/
#include <bits/stdc++.h>
/**
* 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* root){
if(root == NULL) return 0;;
if(root->left == NULL && root-> right == NULL) return -1;
int l = dfs(root->left);
int r = dfs(root->right);
if(l == -1 || r == -1) { ans++; return 1; }
if(l == 1 || r == 1) return 0;
return -1;
}
int minCameraCover(TreeNode* root) {
if(!root->left && !root->right) return 1;
int x = dfs(root);
if(x==-1) ans++;
return ans;
}
};