Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- final int COVERED = 1000;
- public int minCameraCover(TreeNode root) {
- int cameras = 0;
- for(;;) {
- TreeNode top = null, mid = null, bottom = null, current = root;
- while (current != null) {
- top = mid;
- mid = bottom;
- bottom = current;
- current = (current.left != null) ? current.left: current.right;
- }
- if (!isCovered(bottom)) {
- cameras++;
- setCovered(top);
- setCovered(mid);
- if (mid != null) {
- setCovered(mid.left);
- setCovered(mid.right);
- }
- }
- if (mid == null) break;
- cut(mid, bottom);
- }
- return cameras;
- }
- private boolean isCovered(TreeNode node) {
- return node != null && node.val >= COVERED;
- }
- private void setCovered(TreeNode node) {
- if (node != null && !isCovered(node)) node.val += COVERED;
- }
- private void cut(TreeNode from, TreeNode to) {
- if (from.left == to) from.left = null;
- else from.right = null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment