1st Method:(in C)
struct node * immediateAncestor(struct node *root,struct node *node)
{
if(root==NULL)
return NULL;
if(root->left==node || root->right==node)
return root;
else
{
struct node* left,right;
left=immediateAncestor(root->left,node);
right=immediateAncestor(root->right,node);
return (left!=NULL)?left:right;
}
}
2nd Method:(in C++)
node* ancestor(node *root, node *x)
{
if(root == NULL || x==NULL || root == x)
return NULL;
if(root->left==x || root->right==x)
return root;
return (ancestor(root->left,x)||ancestor(root->right,x));
}
No comments:
Post a Comment