Binary Tree Cameras
Master this topic with zero to advance depth.
Binary Tree Cameras
Min cameras.
Level I: BFS (Try all camera placements)
Intuition
A brute force approach would try every possible subset of nodes to place cameras and check if all nodes are covered. Since there are subsets, this is too slow but conceptually simple.
Logic
- Generate all combinations of camera placements.
- For each combination, check if all nodes are covered.
- Return the minimum size of a valid combination.
Detailed Dry Run
Try all 8 combinations for 3 nodes. Min cameras = 1 (at root).
Level II: Dynamic Programming (Recursive with 3 States)
Intuition
For each node, we can track 3 states:
- Node has a camera.
- Node is covered by a child.
- Node is not yet covered (must be covered by parent).
Logic
dp(node, state)returns min cameras for subtree rooted atnodegivenstate. This avoids the greedy assumptions by exploring all valid coverages recursiveley.
Detailed Dry Run
DP(root, hasCamera) returns min of children. DP(root, notCovered) forces parent camera.
Level III: Optimal (Greedy Post-Order)
Intuition
Thought Process
We want to place cameras such that we cover all nodes with the minimum number. A camera at a node covers itself, its parent, and its children.
Greedy Strategy: It's always better to place a camera at a parent of a leaf node rather than the leaf node itself. A camera at the parent covers more nodes.
Node States
- 0: Node is not covered.
- 1: Node has a camera.
- 2: Node is covered but has no camera.
Logic
- If children are not covered (0), parent must have a camera (1).
- If children have a camera (1), parent is covered (2).
- Otherwise, node is not covered (0).
Detailed Dry Run
| Node | Left State | Right State | Node State | Action |
|---|---|---|---|---|
| Leaf | 2 | 2 | 0 | Return 0 (leaf uncovered) |
| Parent | 0 | 0 | 1 | Camera++ (covers leaf) |
| GrandP | 1 | 1 | 2 | Covered by child |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.