#968
Binary Tree Cameras
HardDynamic ProgrammingTreeDepth-First SearchBinary TreeDepth-First SearchDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution uses a depth-first search (DFS) approach with a state-based system to determine if a node is covered, needs a camera, or has a camera. This allows us to efficiently calculate the minimum number of cameras needed.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS traversal of the tree.
- 2Step 2: For each node, determine its state: covered, needs a camera, or has a camera.
- 3Step 3: Count the cameras based on the states of the child nodes.
solution.py23 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def minCameraCover(self, root: TreeNode) -> int:
10 self.cameras = 0
11 def dfs(node):
12 if not node:
13 return 1
14 left = dfs(node.left)
15 right = dfs(node.right)
16 if left == 0 or right == 0:
17 self.cameras += 1
18 return 2
19 return 1 if left == 2 or right == 2 else 0
20 if dfs(root) == 0:
21 self.cameras += 1
22 return self.cameras
23ℹ
Complexity note: The time complexity is O(n) because we visit each node once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Cameras can cover the node itself, its parent, and its children.
- 2A node needs a camera if any of its children are not covered.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.