Thursday, March 22, 2012

y lies in the path between x and z or not in a Binary Tree

Given a binary tree, and 3 nodes x,y,z write a function which returns true if y lies in the path between x and z and false otherwise.

Code:
int find_y_in_xz_path(Tree t, Node *y, Node *z, int yfound)
{
    if(!t)
        return 0;

    if(t == z)
    {
        return yfound;
    }
    else if(t == y)
    {
        yfound = 1;
    }

    if(find_y_in_xz_path(t->left, y, z, yfound))
        return 1;

    return find_y_in_xz_path(t->right, y, z, yfound);

}

int main()
{
    find_y_in_xz_path(x,y,z,0);
}

No comments:

Post a Comment