Microsoft Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Node *FindLCA(Node *root, Node *first, Node *second)
{
if(root==NULL)
return NULL;
if( (root == first) || (root == second) )
return root;
Node *L = findLCA(root->left, first, second);
Node *R = findLCA(root->right, first, second);
if ( L && R )
return root;
else if (L)
return L;
else if (R)
return R;
}
- If the root is one of the nodes searched for than it means the root is the least common ancestor.
- If the two nodes are found in left and right subtrees seperately it again means the root is the LCA.
int lca(Node *Root, int n1, int n2){
int found = 0;
if(Root == NULL) return 0;
if(Root->data == n1 || Root->data == n2)
return 1+lca(Root->left, n1,n2)+lca(Root->right, n1,n2);
found = lca(Root->left, n1,n2)+lca(Root->right, n1,n2);
if(found == 2){
printf("\n%d\n", Root->data);
return 0;
}
return found;
}
int data1;
int data2;
node* LCS(node *root, bool *firstfound, bool *secondfound)
{
if(root == null ) return null;
node *left = LCS(root->left, firstfound, secondfound);
node *right = LCS(root->right, firstfound, secondfound);
if(left > 0 || right > 0)
{
return(left > 0 ? left : right);
}
if(left < 0 && right < 0)
{
return root;
}
else if (left <0 || right < 0)
{
if(firstfound && root->data==data2)
{
return root;
}
else if(secondfound && root->data == data1
{
return root;
}
else
{
return -1000;
}
}
else
{
if(root->data == data1)
{
*firstfound = true;
return -1000;
}
else if (root->data == data2)
{
*secondfound = true;
return -1000;
}
}
return null;
}
community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor
- Anonymous January 13, 2012follow this....