Binary Tree Cameras
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) → intExamples
Example 1
root = [0,0,null,0,0]return = 1Place 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 = 2No single camera can monitor the entire chain-like tree. Two cameras placed at suitable internal nodes are sufficient.
Example 3
root = [0]return = 1The only node must be monitored, so installing one camera on the root is optimal.
Constraints
- The tree contains between
1and1000nodes. - Every node has value
0.
Source note: Amazon OA sighting shared by a FastPrep contributor.