Binary Tree Cameras LeetCode solution in JavaScript

1
var minCameraCover = function (root) {
2
let cam = 0;
3
// 0 --> No covered
4
// 1 --> covered by camera
5
// 2 --> has camera
6
function dfs(root) {
7
if (root === null) return 1;
8

9
const left = dfs(root.left);
10
const right = dfs(root.right);
11

12
if (left === 0 || right === 0) {
13
// child required a camera to covered
14
cam++;
15
return 2;
16
} else if (left === 2 || right === 2) {
17
// child has camera so i am covered
18
return 1;
19
} else {
20
// child is covered but don't have camera,So i want camera
21
return 0;
22
}
23
}
24

25
const ans = dfs(root);
26

27
if (ans === 0) ++cam;
28

29
return cam;
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0