Skip to content

Commit ea9b8d4

Browse files
authored
Binary-Tree-Cameras.cpp (#53)
C++ solution for Binary Tree Cameras https://leetcode.com/problems/binary-tree-cameras/
1 parent b3f6648 commit ea9b8d4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

C++/Binary-Tree-Cameras.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
unordered_set<TreeNode*> covered;
16+
void dfs(TreeNode* root,TreeNode* parent){
17+
if(root==NULL)
18+
return;
19+
dfs(root->left,root);
20+
dfs(root->right,root);
21+
if((parent==NULL && covered.find(root)==covered.end()) || covered.find(root->left)==covered.end() || covered.find(root->right)==covered.end()){
22+
ans++;
23+
covered.insert(root);
24+
covered.insert(parent);
25+
covered.insert(root->left);
26+
covered.insert(root->right);
27+
}
28+
}
29+
int minCameraCover(TreeNode* root) {
30+
covered.insert(NULL);
31+
dfs(root,NULL);
32+
return ans;
33+
}
34+
};

0 commit comments

Comments
 (0)