Question
Leetcode - 968. Binary Tree Cameras
Train of thought
- Using postorder traversal and greedy algorithm;
- We define three states for node:
- NO_COVERED: indicate the current node and its immediate nodes do not install camera;
- INSTALL_CAMERA: indicate the current node install camera
- HAS_COVERED: indicate the current node’s immediate nodes has install camera at least one node
- Especial for the null node, we think it’s state is HAS_COVERED.
- We define three states for node:
- What is the greedy strategy?
- Now give you three immediate node, names parent, left child and right child, and the left child and right child 's state is certain
- We can judge the children’s states to sure the parent node’s state:
- left == HAS_COVERED && right == HAS_COVERED: the parent node’s state is NO_COVERED;
- left == NO_COVERED || right == NO_COVERED: the parent node’s state is INSTALL_CAMERA;
- other: the parent node’s state is HAS_COVERED.
- Especial action is we need to count of the node that its state is INSTALL_CAMERA.
- Last, we using post order traversal to sure happened the child node’s state be determined before the parent node.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private final int NO_COVERED = 0; // indicate the current node and its immediate nodes do not install camera
private final int INSTALL_CAMERA = 1; // indicate the current node install camera
private final int HAS_COVERED = 2; // indicate the current node's immediate nodes has install camera at least one node
private int camears; // the count of install cameras
public int minCameraCover(TreeNode root) {
camears = 0;
if (postTraversal(root) == NO_COVERED) {
camears++;
}
return camears;
}
private int postTraversal(TreeNode root) {
if (root == null) {
return HAS_COVERED;
}
int left = postTraversal(root.left);
int right = postTraversal(root.right);
if (left == HAS_COVERED && right == HAS_COVERED) {
return NO_COVERED;
}
if (left == NO_COVERED || right == NO_COVERED) {
camears++;
return INSTALL_CAMERA;
}
// other states:
// HAS_COVERED && INSTALL_CAMERA
// INSTALL_CAMERA && INSTALL_CAMERA
// above example states shows the root surely be covered
return HAS_COVERED;
}
}
Optimize
nothing