1650. (LCA) Lowest Common Ancestor of a Binary Tree III
Last updated
Last updated
because this question gives parent Node
so put p's all parent Nodes into a set<>
then check all q's all parents are in set? if find, it's LCA!class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
Set<Node> set = new HashSet<>();
Node curr = p;
while (curr != null) {
set.add(curr);
curr = curr.parent;
}
curr = q;
while (curr != null) {
if (set.contains(curr)) {
return curr;
}
curr = curr.parent;
}
return null;
}
}