forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1650.java
46 lines (41 loc) · 1.05 KB
/
_1650.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
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.Set;
public class _1650 {
class Node {
public int val;
public Node parent;
public Node left;
public Node right;
public Node(int val) {
this.val = val;
}
}
public static class Solution1 {
public Node lowestCommonAncestor(Node p, Node q) {
Node a = p;
Node b = q;
while (a != b) {
a = a == null ? p : a.parent;
b = b == null ? q : b.parent;
}
return a;
}
}
public static class Solution2 {
public Node lowestCommonAncestor(Node p, Node q) {
Set<Node> set = new HashSet<>();
while (p != null) {
set.add(p);
p = p.parent;
}
while (q != null) {
if (set.contains(q)) {
return q;
}
q = q.parent;
}
return null;
}
}
}