- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1676.java
67 lines (61 loc) · 2.17 KB
/
_1676.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.HashSet;
importjava.util.Set;
publicclass_1676 {
publicstaticclassSolution1 {
/*
* Since there are conditions for this problem: all values in the tree and given nodes are unique,
* we could simply use a HashSet to track the number of nodes we've found so far during the traversal.
* <p>
* credit: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/discuss/958833/java-100
*/
TreeNodelca = null;
publicTreeNodelowestCommonAncestor(TreeNoderoot, TreeNode[] nodes) {
Set<Integer> target = newHashSet<>();
for (TreeNodenode : nodes) {
target.add(node.val);
}
dfs(root, target);
returnlca;
}
privateintdfs(TreeNoderoot, Set<Integer> target) {
if (root == null) {
return0;
}
intleftCount = dfs(root.left, target);
intrightCount = dfs(root.right, target);
intfoundCount = leftCount + rightCount;
if (target.contains(root.val)) {
foundCount++;
}
if (foundCount == target.size() && lca == null) {
lca = root;
}
returnfoundCount;
}
}
publicstaticclassSolution2 {
/*
* Silly brute force way.
*/
publicTreeNodelowestCommonAncestor(TreeNoderoot, TreeNode[] nodes) {
TreeNodeans = nodes[0];
for (inti = 1; i < nodes.length; i++) {
ans = lca(root, ans, nodes[i]);
}
returnans;
}
privateTreeNodelca(TreeNoderoot, TreeNodep, TreeNodeq) {
if (root == null || root == p || root == q) {
returnroot;
}
TreeNodeleft = lca(root.left, p, q);
TreeNoderight = lca(root.right, p, q);
if (left != null && right != null) {
returnroot;
}
returnleft != null ? left : right;
}
}
}