Advertisement
Guest User

Grokking 207-b

a guest
Feb 15th, 2022
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17.  
  18. int COVER_WITH_CAMERA = 0;
  19. int COVER_NO_CAMERA = 1;
  20. int NOT_COVER = 2;
  21.  
  22. int numCameras;
  23. public int minCameraCover(TreeNode root) {
  24. numCameras = 0;
  25.  
  26. int status = getStatus(root);
  27.  
  28. // if root's status is not cover, add a camera to root node
  29. if (status == NOT_COVER) {
  30. numCameras++;
  31. }
  32.  
  33. return numCameras;
  34. }
  35.  
  36. public int getStatus(TreeNode node) {
  37. if (node == null) {
  38. return COVER_NO_CAMERA;
  39. }
  40.  
  41. int left = getStatus(node.left);
  42. int right = getStatus(node.right);
  43.  
  44. if (left == NOT_COVER || right == NOT_COVER) {
  45. // if left or right is not covered, add a camera at current node
  46. numCameras++;
  47. return COVER_WITH_CAMERA;
  48. }
  49.  
  50. if (left == COVER_NO_CAMERA && right == COVER_NO_CAMERA) {
  51. return NOT_COVER;
  52. }
  53.  
  54. return COVER_NO_CAMERA;
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement