ogv

Untitled

ogv
Sep 22nd, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. class Solution {
  2.     final int COVERED = 1000;
  3.    
  4.     public int minCameraCover(TreeNode root) {
  5.         int cameras = 0;
  6.        
  7.         for(;;) {
  8.             TreeNode top = null, mid = null, bottom = null, current = root;
  9.             while (current != null) {
  10.                 top = mid;
  11.                 mid = bottom;
  12.                 bottom = current;
  13.                 current = (current.left != null) ? current.left: current.right;
  14.             }
  15.            
  16.             if (!isCovered(bottom)) {
  17.                 cameras++;
  18.                 setCovered(top);
  19.                 setCovered(mid);
  20.                 if (mid != null) {
  21.                     setCovered(mid.left);
  22.                     setCovered(mid.right);
  23.                 }
  24.             }
  25.            
  26.             if (mid == null) break;
  27.                          
  28.             cut(mid, bottom);
  29.         }
  30.                      
  31.         return cameras;
  32.     }                
  33.    
  34.     private boolean isCovered(TreeNode node) {
  35.         return node != null && node.val >= COVERED;
  36.     }
  37.    
  38.     private void setCovered(TreeNode node) {
  39.         if (node != null && !isCovered(node)) node.val += COVERED;
  40.     }
  41.        
  42.     private void cut(TreeNode from, TreeNode to) {        
  43.         if (from.left == to) from.left = null;
  44.         else from.right = null;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment