Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 968 Binary Tree Cameras - Implementation

Post-order with state

Post-order DFS. Return the state of each node. Count cameras (state 00 nodes). Handle root specially: if root returns "not covered", we must add a camera at root. Null children: treat as "covered" (state 11) so they don't force unnecessary cameras. Time: O(n)O(n), Space: O(h)O(h). Each node decides based on children's states in constant time. Start from leaves and work up. Leaves are never optimal camera locations because their parents cover more.

Time complexity: O(n)O(n).

Space complexity: O(h)O(h).