179. Write a function to get lowest common ancestor in "binary tree"
Microsoft Interview Questions and Answers
(Continued from previous question...)
179. Write a function to get lowest common ancestor in "binary tree"
Question:
Write a function to get lowest common ancestor in "binary tree"
maybe an answer:
typedef struct node{
int val;
struct node *left;
struct node *right;
} tNode;
tNode * ClosestCommonAnscestor( tNode *root, tNode *key1, tNode *key2)
{
if( root == NULL )
{
return NULL;
}
else if( root == key1 || root == key2 )
{
return root;
}
else
{
tNode *l= NULL, *r = NULL ;
l = ClosestCommonAnscestor( root->left, Key1, key2 );
r = ClosestCommonAnscestor( root->right, Key1, key2 );
if( (l != NULL) && (r != NULL) )
{
return root;
}
else
{
return l ? l : r;
}
}
}
(Continued on next question...)
Other Interview Questions
|