Lowest Common Ancestor of multiple nodes in a n-ary tree


Keywords:java 


Question: 

I am trying to implement LCA of multiple nodes in an n-ary tree in java. I am working with parse trees of sentences, So its reasonable to assume that number of children of a node <= 6. Multiple nodes here are two phrases(continuous word sequence) in a sentence. Let k be the number of nodes involved.

One way is to find the LCA of two nodes for k/2 pairs and we will get k/2 nodes. Now recurse on these k/2 nodes. The order will be O(nlog k), where O(n) is the complexity of linear LCA finding algorithms. Can I do it more efficiently ?


1 Answer: 

I solved the problem using the fact that the nodes of the phrases are continuous i.e. have continuous indices in the list of leaf nodes of a parse tree.

Let segment1 have indices from start1 to end1. Same be the case for segment2 = (start2,end2).

The Required Common Ancestor of (start1, end1) and (start2, end2) is the common ancestor of nodes with indices min(start1,start2) and max(end1,end2).