
Sponsored
Sponsored
The greedy DFS solution is based on a bottom-up approach. We classify each node into one of three states: covered by a camera, has a camera, or needs a camera. A node needs a camera if its children are not covered. We use a post-order DFS strategy to ensure all children are addressed before deciding the current node's state. The optimal way to cover a subtree is to place a camera on nodes whose children are not covered.
Time Complexity: O(n), where n is the number of nodes in the tree, due to the DFS traversal of every node.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack space.
1#include <iostream>
2#include <algorithm>
3
4struct TreeNode {
5 int val;
6 TreeNode *left;
7 TreeNode *right;
8 TreeNode() : val(0), left(nullptr), right(nullptr) {}
9};
10
11class Solution {
12public:
13 int minCameras = 0;
14
15 int dfs(TreeNode* node) {
16 if (node == nullptr) return 2;
17 int left = dfs(node->left);
18 int right = dfs(node->right);
19
20 if (left == 0 || right == 0) {
21 minCameras++;
22 return 1;
23 }
24 return (left == 1 || right == 1) ? 2 : 0;
25 }
26
27 int minCameraCover(TreeNode* root) {
28 if (dfs(root) == 0) minCameras++;
29 return minCameras;
30 }
31};This C++ solution similarly performs a DFS on the tree, using `minCameras` as a count of the cameras placed. If a node's children need coverage (state 0), a camera is placed at the current node.
This approach leverages dynamic programming through a recursive function with memoization to reduce redundant calculations. Each node can have three states represented in a tuple: it has a camera, it's covered but doesn't have a camera, or it's not covered. Using this state information, the solution calculates camera placements strategically.
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(n), due to memoization storage.
1from functools import lru_cache
2
3class TreeNode:
4 def
This solution uses dynamic programming with memoization to avoid redundant recursive calls. The function `dfs` returns a tuple of three states for each node: the cost of having a camera, being covered without a camera, and not being covered.
The first element, `dp0`, calculates cost when a camera is placed at the current node. The second, `dp1`, calculates when the node is covered without having a camera, and the third, `dp2`, calculates when the node itself isn't covered.