This question evaluates understanding of tree algorithms and recursive DFS traversal for computing the lowest common ancestor in an N-ary tree, including handling node references, subtree detection, and correctness in a single traversal.
You are given the root of a rooted N-ary tree (each node can have zero or more children) and two distinct nodes p and q that belong to the tree.
Design an algorithm to find the lowest common ancestor (LCA) of p and q.
The LCA of two nodes p and q in a rooted tree is defined as the lowest (i.e., deepest) node in the tree that has both p and q as descendants (where we allow a node to be a descendant of itself).
p
and
q
to distinct nodes in the same tree.
p
and
q
.
p
or
q
was found in that node’s subtree.
children
list).
Explain the algorithm and then provide the implementation.