Binary Tree Cameras

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
        0
       /
      0
     / \
    0   0
Inputroot = [0,0,null,0,0]
Output1
One camera is enough to monitor all nodes if placed as shown.
Example 2
        0
       /
      0
     /
    0
   /
  0
   \
    0
Inputroot = [0,0,null,0,null,0,null,null,0]
Output2
At least two cameras are needed to monitor all nodes of the tree; the shown placement is one valid configuration.

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val == 0

Asked at 14 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate