Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Binary Tree Cameras

Hard Acceptance 55.21% Points 40.00

You are given the root of a binary tree. You may install cameras on nodes, where each camera monitors:

  • The node on which it is installed.
  • Its parent.
  • Its immediate left and right children.

Your task is to determine the minimum number of cameras required so that every node in the binary tree is monitored.

Return the minimum number of cameras needed.

Examples
Example 1

image Input: root = [0,0,null,0,0]
Output: 1
Explanation: A single camera placed on the second node can monitor all nodes in the tree.

Example 2

image Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are required to monitor every node in this skewed tree.

Example 3

image Input: root = [0]
Output: 1
Explanation: A single node needs one camera to be monitored.

Constraints
    • 1 = Number of nodes = 1000
    • -10? = Node.data = 10?
Companies
Microsoft Mastercard
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions