Advertisement
Guest User

Grokking 207

a guest
Feb 15th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. class Solution {
  2.  
  3. Set<TreeNode> covered;
  4. int numCameras = 0;
  5. public int minCameraCover(TreeNode root) {
  6. covered = new HashSet<>();
  7. numCameras = 0;
  8.  
  9. // null node is always covered
  10. covered.add(null);
  11.  
  12. getCover(root, null);
  13.  
  14. // if root node is not covered, add a camera at root node
  15. if (!covered.contains(root)) {
  16. numCameras++;
  17. }
  18.  
  19. return numCameras;
  20. }
  21.  
  22. public void getCover(TreeNode node, TreeNode parent) {
  23. if (node != null) {
  24. getCover(node.left, node);
  25. getCover(node.right, node);
  26.  
  27. if (parent == null && !covered.contains(node) ||
  28. !covered.contains(node.left) ||
  29. !covered.contains(node.right)) {
  30. // add a camera to current node
  31. numCameras++;
  32.  
  33. // update covered nodes
  34. covered.add(node);
  35. covered.add(parent);
  36. covered.add(node.left);
  37. covered.add(node.right);
  38. }
  39. }
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement