Binary Tree Cameras in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary tree; we place cameras on the nodes of the tree. Now each camera at a node can monitor its parent, itself, and its children. We have to find the minimum number of cameras needed to monitor all nodes of the tree.

So, if the input is like −

then the output will be 1, because only one camera is enough to track all.

To solve this, we will follow these steps −

  • Define one set called covered, of type TreeNode (Tree node has left, right and data field)

  • Define a function solve(), this will take node, parent,

  • if node is null, then −

    • return

  • solve(left of node, node)

  • solve(right of node, node)

  • if (parent is same as NULL and (node, left of node, right of node) nothing is covered, then −

    • (increase ans by 1)

    • insert node into covered

    • insert left of node into covered

    • insert right of node into covered

    • insert parent into covered

  • From the main method do the following,

  • ans := 0

  • insert NULL into covered

  • solve(root, NULL)

  • return ans

Let us see the following implementation to get better understanding −


#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
class Solution {
   set<TreeNode*> covered;
   int ans;
   int minCameraCover(TreeNode* root){
      ans = 0;
      solve(root, NULL);
      return ans;
   void solve(TreeNode* node, TreeNode* parent){
      if (!node)
      solve(node->left, node);
      solve(node->right, node);
      if ((parent == NULL && covered.find(node) == covered.end())
      || covered.find(node->left) == covered.end() || covered.find(node-
      >right) == covered.end()) {
   Solution ob;
   TreeNode *root = new TreeNode(1);
   root->left = new TreeNode(1);
   root->left->left = new TreeNode(1); root->left->right = new
   cout << (ob.minCameraCover(root));




Published on 08-Jun-2020 14:15:16