968. Binary Tree Cameras
Description
You are given the root
of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: root = [0,0,null,0,0] Output: 1 Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: root = [0,0,null,0,null,0,null,null,0] Output: 2 Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. Node.val == 0
Solutions
Solution: Greedy + Depth-First Search
- Time complexity: O(n)
- Space complexity: O(h)
JavaScript
js
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const minCameraCover = function (root) {
const LEAF = 0;
const CAMERA = 1;
const PARENT = 2;
let result = 0;
const setupCamera = node => {
if (!node) return PARENT;
const left = setupCamera(node.left);
const right = setupCamera(node.right);
if (left === LEAF || right === LEAF) {
result += 1;
return CAMERA;
}
return left === CAMERA || right === CAMERA ? PARENT : LEAF;
};
const node = setupCamera(root);
return result + (node === LEAF ? 1 : 0);
};