FastPrepBinary Tree Cameras

Binary Tree Cameras

Amazon logoAmazon● HardFULLTIMEOAPHONE SCREEN

Problem statement

You are given the root of a binary tree. You may install cameras on its nodes.

A camera installed at a node monitors that node, its parent if one exists, and its immediate children.

Return the minimum number of cameras needed so that every node in the tree is monitored.

Function

minCameraCover(root: TreeNode) → int

Examples

Example 1

root = [0,0,null,0,0]return = 1

Place one camera on the second node in the level-order representation. It monitors its parent, itself, and both of its children, so every node is covered.

Example 2

root = [0,0,null,0,null,0,null,null,0]return = 2

No single camera can monitor the entire chain-like tree. Two cameras placed at suitable internal nodes are sufficient.

Example 3

root = [0]return = 1

The only node must be monitored, so installing one camera on the root is optimal.

Constraints

  • The tree contains between 1 and 1000 nodes.
  • Every node has value 0.

Source note: Amazon OA sighting shared by a FastPrep contributor.

More Amazon problems

See Amazon hiring insights
Saved
public int minCameraCover(TreeNode root) {
    // Write your solution here.
}
root[0,0,null,0,0]
expected1
Checking account…