This question has been asked a lot by Meta (formerly known as Facebook) in the past 3 months.

The question is categorised as a medium, but if you look at the class structure of the tree, you’ll realise that the answer is pretty straightforward. You could find the LCA by using previous approaches like searching through the entire tree and then getting the LCA, but here we’ve access to the parent node as well in the Node class. Also both, p and q exist in the tree.
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
So all we’ve to do is to build a path set from either p or q to the root. Once this set is built, we then travel from the other node to the root of the binary tree. Once we find the node in the path set, that’s the LCA.

In this example, our path set from p to root will be {5,3}. We then start at q and iterate towards the root, carefully examining each node along the way. We first check if 4 is in the path; if it is not found, then we move up to 2, and check again. We then move up to its parent 5. Here we find 5 in the path, so we return 5.
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
path = set()
while p:
path.add(p)
p = p.parent
while True:
if q in path:
return q
else:
q = q.parent
Here we built a path set from p to root. Then we initialise another while loop, and it’s set to run indefinitely as we know LCA will exist as both p and q are in the tree. At each step we take towards the root, we check if q exists in the path set, the moment we find it, that’s the LCA.
Hope this was helpful and let me know in the comments if you want me to cover other LeetCode questions or machine learning topics.


