algorithmtreebinary-treeleast-common-ancestor

Find the least common parent in a binary tree?


This question might have been asked by a lot of guys but, it is kinda different. We have a binary tree. And you are given two nodes p & q. We have to find the least common parent. But you dont have root node pointer which points to the root. You are provided with two inbuilt functions which are:

1) BOOL same(node *p, node *q); -> returns true if the nodes are same or else false.

2) node* parentNode(node *c); -> returns a node which is the parent of the current node.

If the node c is actually root then parentNode function will return you with aNULL value. Using the functions we have to find the least common parent of the tree.


Solution

  • Assuming C++:

    node* leastCommonParent(node *p, node *q)
    {
        node *pParent = parentNode(p);
        while(pParent != 0)
        {
            node *qParent = parentNode(q);
            while(qParent != 0)
            {
                if (0 == same(pParent, qParent))
                    return pParent;
                qParent = parentNode(qParent);
            }
            pParent = parentNode(pParent);
        }
        return 0;
    }
    

    UPDATE: A version without explicitly declared variables using recursion follows. I'm sure it can be improved and would probably never use it in production code in the current form.

    node* qParent(node *p, node *q)
    {
        if (p == 0 || q == 0)
            return 0;
        if (same(p, q) == 0)
            return p;
        return qParent(p, q->parent);
    }
    
    node* pParent(node *p, node *q)
    {
        return qParent(p, q) ? qParent(p, q) : pParent(p->parent, q);
    }
    
    node * result = pParent(p, q);