Skip to content

Commit 27a36c0

Browse files
authored
Create 968. Binary Tree Cameras
1 parent 3845321 commit 27a36c0

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

968. Binary Tree Cameras

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
int cam;
3+
Set<TreeNode> covered;
4+
public int minCameraCover(TreeNode root) {
5+
if(root == null) return 0;
6+
cam = 0;
7+
covered = new HashSet<>();
8+
covered.add(null); // Skip the leaf nodes and start from one level above.
9+
dfs(root, null);
10+
return cam;
11+
}
12+
13+
public void dfs(TreeNode node, TreeNode parent){
14+
if(node != null) {
15+
dfs(node.left, node);
16+
dfs(node.right, node);
17+
18+
//Check if i need to add camera at node.
19+
// Parent is null & node is uncovered
20+
// OR
21+
// if any of its left or right child are not covered
22+
23+
if(parent == null && !covered.contains(node)
24+
|| !covered.contains(node.left) || !covered.contains(node.right)) {
25+
cam++;
26+
covered.add(node);
27+
covered.add(parent);
28+
covered.add(node.left);
29+
covered.add(node.right);
30+
}
31+
32+
}
33+
}
34+
}
35+
36+
class Solution {
37+
int cam = 0;
38+
public int minCameraCover(TreeNode root) {
39+
// (0) -> cam + 1 ,(1,2) --> cam
40+
return dfs(root)==0 ? cam+1 : cam;
41+
}
42+
43+
// 2 --> Has Camera
44+
// 1 -> Covered with the camera
45+
// 0 --> No camera is covering this node
46+
public int dfs(TreeNode node) {
47+
if(node == null) return 1;
48+
int left = dfs(node.left);
49+
int right = dfs(node.right);
50+
//Check if we need to add a camera
51+
if(left == 0 || right == 0) {
52+
cam++;
53+
return 2;
54+
}
55+
else if(left == 2 || right == 2) return 1;
56+
else return 0;
57+
58+
}
59+
}

0 commit comments

Comments
 (0)