Practice › Trees
Binary Tree Cameras
Hard · Trees · Asked at Google, Amazon, Meta
A camera placed on a node watches the node itself, its parent and its children. Print the minimum number of cameras needed to watch every node of the tree.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The minimum number of cameras.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- values are positive (they do not matter)
Greedy from the leaves up: never put a camera on a leaf — its parent covers more. Each node returns a state: 0 = not covered, 1 = has a camera, 2 = covered without a camera. If a child is not covered, put a camera here; else if a child has a camera, this node is covered; else it is not covered. Add one camera if the root ends up uncovered.
Example 1
Input
5 1 1 -1 1 1
Output
1
Example 2
Input
9 1 1 -1 1 -1 1 -1 -1 1
Output
2
Hints
- A camera on a leaf only covers the leaf and its parent; a camera on the parent covers strictly more.
- Decide bottom-up: each node reports whether it is uncovered, has a camera, or is covered.
- If any child is uncovered, the node must hold a camera.
Approach
Process nodes in post-order (reversed preorder, so no recursion). Missing children count as "covered". For a node: if a child is uncovered (0), place a camera here (state 1, count it); else if a child has a camera, the node is covered (2); else it is uncovered (0) and its parent must handle it. If the root ends uncovered, add one more camera. This greedy postpones every camera as high as possible, which is optimal.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node *left = nullptr, *right = nullptr;
int state = 2;
};
int main() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
Node *root = new Node();
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node());
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node());
i++;
}
vector<Node *> order, st = {root};
while (!st.empty()) {
Node *n = st.back();
st.pop_back();
order.push_back(n);
if (n->left) st.push_back(n->left);
if (n->right) st.push_back(n->right);
}
int cams = 0;
for (int j = (int) order.size() - 1; j >= 0; j--) {
Node *n = order[j];
int l = n->left ? n->left->state : 2, r = n->right ? n->right->state : 2;
if (l == 0 || r == 0) {
cams++;
n->state = 1;
} else if (l == 1 || r == 1) n->state = 2;
else n->state = 0;
}
cout << cams + (root->state == 0 ? 1 : 0) << "\n";
return 0;
}Python solution
import sys
from collections import deque
data = list(map(int, sys.stdin.read().split()))
a = data[1 : 1 + data[0]]
# children[i] = [left, right] as node indices (or -1); build from level order
left, right = [-1], [-1]
q = deque([0])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
left[cur] = len(left)
left.append(-1)
right.append(-1)
q.append(left[cur])
i += 1
if i < len(a) and a[i] != -1:
right[cur] = len(left)
left.append(-1)
right.append(-1)
q.append(right[cur])
i += 1
order, stack = [], [0]
while stack:
u = stack.pop()
order.append(u)
if left[u] >= 0:
stack.append(left[u])
if right[u] >= 0:
stack.append(right[u])
state = [2] * len(left)
cams = 0
for u in reversed(order):
l = state[left[u]] if left[u] >= 0 else 2
r = state[right[u]] if right[u] >= 0 else 2
if l == 0 or r == 0:
cams += 1
state[u] = 1
elif l == 1 or r == 1:
state[u] = 2
else:
state[u] = 0
print(cams + (1 if state[0] == 0 else 0))Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
Node left, right;
int state = 2;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int k = (int) in.nval;
long[] a = new long[k];
for (int i = 0; i < k; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
Node root = new Node();
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && a[i] != -1) q.add(cur.left = new Node());
i++;
if (i < k && a[i] != -1) q.add(cur.right = new Node());
i++;
}
ArrayList<Node> order = new ArrayList<>();
ArrayDeque<Node> st = new ArrayDeque<>();
st.push(root);
while (!st.isEmpty()) {
Node n = st.pop();
order.add(n);
if (n.left != null) st.push(n.left);
if (n.right != null) st.push(n.right);
}
int cams = 0;
for (int j = order.size() - 1; j >= 0; j--) {
Node n = order.get(j);
int l = n.left != null ? n.left.state : 2, r = n.right != null ? n.right.state : 2;
if (l == 0 || r == 0) {
cams++;
n.state = 1;
} else if (l == 1 || r == 1) n.state = 2;
else n.state = 0;
}
System.out.println(cams + (root.state == 0 ? 1 : 0));
}
}