-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreeCameras.java
41 lines (33 loc) · 1.04 KB
/
BinaryTreeCameras.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.smlnskgmail.jaman.leetcodejava.hard;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.HashSet;
import java.util.Set;
// https://leetcode.com/problems/binary-tree-cameras/
public class BinaryTreeCameras {
private final TreeNode input;
private int result;
public BinaryTreeCameras(TreeNode input) {
this.input = input;
}
public int solution() {
Set<TreeNode> cov = new HashSet<>();
cov.add(null);
dfs(cov, input, null);
return result;
}
private void dfs(Set<TreeNode> cov, TreeNode node, TreeNode par) {
if (node != null) {
dfs(cov, node.left, node);
dfs(cov, node.right, node);
if (par == null && !cov.contains(node)
|| !cov.contains(node.left)
|| !cov.contains(node.right)) {
result++;
cov.add(node);
cov.add(par);
cov.add(node.left);
cov.add(node.right);
}
}
}
}