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.
Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
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.
[1, 1000].Node.val == 0In this problem, we need to cover all nodes of a binary tree with the minimum number of cameras. A straightforward brute force approach would be to consider placing a camera at every node, which clearly isn't efficient. Instead, we can use a recursive approach where we attempt to minimize the number of cameras required by deciding the optimal placement of each camera during the traversal of the tree.
We third introduce states for nodes:
0 if the node is covered1 if the node is monitored by a camera placed at one of its children2 if the node has a cameraThe base idea is: