Binary Tree Cameras LeetCode solution in Java

1
/**
2
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
3
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,
4
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }
5
*/
6
class Solution {
7
private int count = 0;
8

9
public int minCameraCover(TreeNode root) {
10
if (helper(root) == -1) count++;
11
return count;
12
}
13

14
// post order
15
// 0 - have camera
16
// 1 - covered
17
// -1 - not covered
18
public int helper(TreeNode root) {
19
if (root == null) return 1;
20
int left = helper(root.left);
21
int right = helper(root.right);
22
if (left == -1 || right == -1) {
23
count++;
24
return 0;
25
}
26
if (left == 0 || right == 0) return 1;
27

28
return -1;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0