Web Toolbar by Wibiya

Pages

Friday, January 20, 2012

Print ancestors of a node in a Binary Tree.

Solution #1: Here is the code,

int isAncestor(struct node* root, int n)
{
    if(root == NULL)
        return 0;

    if(root->data == n)
        return 1;

    if(isAncestor(root->left, n) || isAncestor(root->right, n))
    {
        printf("%d\n", root->data);
        return 1;
    }

    return 0;
}

1 comment:

admin said...

How about this code which does this without recursion:

void printAncestors( struct node *root, int num )
{
if ( root == NULL )
return ;
while(1)
{
if( root->val == num)
return ;

printf("%d\t",root->val);
if( root->val > num )
root = root->left ;
else
root = root->right ;
}

}