forked from vaibhavnirmal2001/DSA-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path968-Binary_Tree_Cameras.java
45 lines (40 loc) · 1.03 KB
/
968-Binary_Tree_Cameras.java
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
// Leetcode 968
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int camera = 0;
public int minCameraCover(TreeNode root) {
if(root == null) return 0;
return camera(root) == -1 ? camera + 1 : camera;
}
// 1 -> My parent/children have a camera
// 0 -> I have a camera
// -1 -> I need a camera
public int camera(TreeNode root){
if(root == null)
return 1;
int left = camera(root.left);
int right = camera(root.right);
if(left == -1 || right == -1){
camera++;
return 0;
}
if(left == 0 || right == 0){
return 1;
}
return -1;
}
}