Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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 {
- int COVER_WITH_CAMERA = 0;
- int COVER_NO_CAMERA = 1;
- int NOT_COVER = 2;
- int numCameras;
- public int minCameraCover(TreeNode root) {
- numCameras = 0;
- int status = getStatus(root);
- // if root's status is not cover, add a camera to root node
- if (status == NOT_COVER) {
- numCameras++;
- }
- return numCameras;
- }
- public int getStatus(TreeNode node) {
- if (node == null) {
- return COVER_NO_CAMERA;
- }
- int left = getStatus(node.left);
- int right = getStatus(node.right);
- if (left == NOT_COVER || right == NOT_COVER) {
- // if left or right is not covered, add a camera at current node
- numCameras++;
- return COVER_WITH_CAMERA;
- }
- if (left == COVER_NO_CAMERA && right == COVER_NO_CAMERA) {
- return NOT_COVER;
- }
- return COVER_NO_CAMERA;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement