Closest Ancestor
-
Hi all, I am writing a program to find the closest ancestor in a binary tree (not BST). I found a sample working code:
mynode *closestAncestor(mynode* root, mynode* p, mynode* q)
{
mynode *l, *r, *tmp;if(root == NULL)
{
return(NULL);
}if(root->left==p || root->right==p || root->left==q || root->right==q)
{
return(root);
}
else
{
l = closestAncestor(root->left, p, q);
r = closestAncestor(root->right, p, q);if(l!=NULL && r!=NULL) { return(root); } else { tmp = (l!=NULL) ? l : r; return(tmp); }
}
}I am trying to do something like the following (passing only the data values and finding only the data value of ancestor, not concerned with its pointer)
int closestanc(node * root, int n1, int n2)
{
int l, r;
if(root == NULL)
return -1;
if(root->right->data == n1 || root->right->data == n2 || root->left->data == n1 || root->left->data == n2)
return root->data;
else
{
l = closestanc(root->left, n1, n2);
r = closestanc(root->right, n1, n2);
if(l!= -1 && r!= -1)
return root->data;
else
return (l != -1 ? l : r);
}
}But this thing doesn't work. Can you please point out where I am doing it wrong ?
-
Hi all, I am writing a program to find the closest ancestor in a binary tree (not BST). I found a sample working code:
mynode *closestAncestor(mynode* root, mynode* p, mynode* q)
{
mynode *l, *r, *tmp;if(root == NULL)
{
return(NULL);
}if(root->left==p || root->right==p || root->left==q || root->right==q)
{
return(root);
}
else
{
l = closestAncestor(root->left, p, q);
r = closestAncestor(root->right, p, q);if(l!=NULL && r!=NULL) { return(root); } else { tmp = (l!=NULL) ? l : r; return(tmp); }
}
}I am trying to do something like the following (passing only the data values and finding only the data value of ancestor, not concerned with its pointer)
int closestanc(node * root, int n1, int n2)
{
int l, r;
if(root == NULL)
return -1;
if(root->right->data == n1 || root->right->data == n2 || root->left->data == n1 || root->left->data == n2)
return root->data;
else
{
l = closestanc(root->left, n1, n2);
r = closestanc(root->right, n1, n2);
if(l!= -1 && r!= -1)
return root->data;
else
return (l != -1 ? l : r);
}
}But this thing doesn't work. Can you please point out where I am doing it wrong ?
You say it doesn't work, but you don't explain how it doesn't work. Does it error, or just give the wrong answer? From what I can see, you check to see if root = NULL, which is good. But then you compare the values of root->right->data and root->left->data against n1 and n2. But what if root->right or root->left is NULL? Then it's data will be undefined, and the compare will fail. If it doesn't error out at this point, it may just go on to the else condition, which is fine. But as I said, I don't know how it is failing.
Roy.