Skip to content

Commit 8f38205

Browse files
committed
Add solution #968
1 parent 618f758 commit 8f38205

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,052 LeetCode solutions in JavaScript
1+
# 1,053 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -776,6 +776,7 @@
776776
965|[Univalued Binary Tree](./solutions/0965-univalued-binary-tree.js)|Easy|
777777
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
778778
967|[Numbers With Same Consecutive Differences](./solutions/0967-numbers-with-same-consecutive-differences.js)|Medium|
779+
968|[Binary Tree Cameras](./solutions/0968-binary-tree-cameras.js)|Hard|
779780
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|
780781
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
781782
977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy|

solutions/0968-binary-tree-cameras.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 968. Binary Tree Cameras
3+
* https://leetcode.com/problems/binary-tree-cameras/
4+
* Difficulty: Hard
5+
*
6+
* You are given the root of a binary tree. We install cameras on the tree nodes where each camera
7+
* at a node can monitor its parent, itself, and its immediate children.
8+
*
9+
* Return the minimum number of cameras needed to monitor all nodes of the tree.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @return {number}
23+
*/
24+
var minCameraCover = function(root) {
25+
let cameras = 0;
26+
const rootState = traverse(root);
27+
return rootState === 0 ? cameras + 1 : cameras;
28+
29+
function traverse(node) {
30+
if (!node) return 1;
31+
32+
const left = traverse(node.left);
33+
const right = traverse(node.right);
34+
35+
if (left === 0 || right === 0) {
36+
cameras++;
37+
return 2;
38+
}
39+
40+
if (left === 2 || right === 2) {
41+
return 1;
42+
}
43+
44+
return 0;
45+
}
46+
};

0 commit comments

Comments
 (0)