## Microsoft Interview Question

Software Engineer in Tests- 0of 0 votes
Given an n-ary tree, find the closest common ancestor ? Discuss the time complexity and write testcases.

**Country:**United States

```
class FindClosestCommonAncestorNaryTree
{
public Node Solve(Node tree, Node node1, Node node2)
{
List<Node> ancestors1 = new List<Node>();
List<Node> ancestors2 = new List<Node>();
tree.GetAncestorsOf(node1, ref ancestors1);
tree.GetAncestorsOf(node2, ref ancestors2);
foreach (Node n1 in ancestors1)
{
foreach (Node n2 in ancestors2)
{
if (n1 == n2)
{
return n1;
}
}
}
return null;
}
}
public class Node
{
public int data;
public List<Node> children = null;
public Node(int _data, List<Node> _children)
{
data = _data;
children = _children;
}
internal bool GetAncestorsOf(Node node, ref List<Node> ancestors)
{
if (this == node)
{
return true;
}
if (children != null)
{
foreach (Node child in children)
{
if (child.GetAncestorsOf(node, ref ancestors))
{
ancestors.Add(this);
return true;
}
}
}
return false;
}
}
```

get ancestor list of both nodes n1 and n2.

compare top ancestor of n1 with top ancestor of n2.

if equal, got to the a level below of ancestor for n1 & n2 and compare in iterative manner.

at some point, either they will not be equal or one of the ancestor will be null.

return the previous compared ancestor.

Lowest Common Ancestor

findLCA(Node head,int Key1,int Key2)

{

if( head==null) return;

if(Key1>head.Key && Key2> head.Key)

{

findLCA(head.Right,Key1,Key2)

}

else if(Key1<head.Key && Key2<head.Key)

{

findLCA(head.Left,Key1,Key2)

}

else

return head;

}

```
def lca_dfs(self,key1,key2,root):
execut=[]
execut.extend([key1,key2])
lst1=self.dfs(execut[0],root)
lst2=self.dfs(execut[1],root)
intrsctn=(set(lst1)).intersection(set(lst2))
lst=list(intrsctn)
if len(lst)>0:
print "lca is:",lst[len(lst)-1]
else:
print "lca is:",root.val
def dfs(self,key,root):
if len(root.child)==0:
return
for nde in root.child:
if nde.val==key:
return ([])
else:
fnd=self.dfs(key,nde)
if isinstance(fnd,list):
fnd.append(nde.val)
return fnd
return fnd
```

```
def lca_dfs(self,key1,key2,root):
execut=[]
execut.extend([key1,key2])
lst1=self.dfs(execut[0],root)
lst2=self.dfs(execut[1],root)
intrsctn=(set(lst1)).intersection(set(lst2))
lst=list(intrsctn)
if len(lst)>0:
print "lca is:",lst[len(lst)-1]
else:
print "lca is:",root.val
def dfs(self,key,root):
if len(root.child)==0:
return
for nde in root.child:
if nde.val==key:
return ([])
else:
fnd=self.dfs(key,nde)
if isinstance(fnd,list):
fnd.append(nde.val)
return fnd
return fnd
```

Pretty much the same as LCA of a BST, we just need to traverse all children.

- Alberto Munguia April 23, 2013