/**
* Lowest Common Ancestor of an N-ary Tree
*
* Approach: Bottom-up recursion / Postorder DFS
*
* Similar to LCA in a binary tree, but instead of searching
* only left and right subtrees, we search all child subtrees.
*
* Each recursive call returns:
* 1. null - if neither p nor q exists in the subtree.
* 2. p or q - if only one target exists in the subtree.
* 3. LCA - if both targets exist in the subtree.
*
* Assumption: Both target nodes exist in the original tree.
*/
var lowestCommonAncestor = function(root, p, q) {
// Base case 1:
// An empty subtree contains neither target.
if (!root) return null;
// Base case 2:
// If the current node is one of the targets, return it.
// It may itself be the LCA if the other target is
// one of its descendants.
if (root === p || root === q) return root;
// Store non-null results returned by the child subtrees.
// A result can be p, q, or an already determined LCA.
const keyNodes = [];
// Unlike a binary tree, an N-ary tree can have any
// number of children. Recursively search each child.
for (const child of root.children) {
const keyNode = lowestCommonAncestor(child, p, q);
// Ignore subtrees that contain neither target.
if (keyNode !== null) {
keyNodes.push(keyNode);
}
}
// Case 1: Two different child subtrees contain the targets.
// The current node is the split point and therefore the LCA.
if (keyNodes.length === 2) return root;
// Case 2: Only one child subtree returned a non-null result.
// It may contain one target or an already determined LCA.
// Simply propagate that result upward.
if (keyNodes.length === 1) return keyNodes[0];
// Case 3: Neither the current node nor any of its
// child subtrees contains either target.
return null;
};
// 7. Time and space complexity
// Time Complexity: O(N)
// In the worst case, we visit every node in the tree once.
// Although there is a for loop inside the recursive function, the total number of child relationships in a tree with N nodes is N - 1.
// Therefore, the total work across all recursive calls is linear.
// Space Complexity: O(H)
// Here, H is the height of the tree.
// The recursion stack contains at most H active recursive calls (up to an additive constant, depending on the height convention).
// You might wonder whether creating a keyNodes array in every recursive call increases the space complexity.
// However, each keyNodes array can hold at most two nodes, because we are searching for only two targets. Therefore, each recursive call uses O(1) additional space.
// \[
// SC = O(H)
// \]
// Worst-case space complexity is O(N) for a skewed tree.