My Solution to Lowest Common Ancestor of a Binary Tree(Down-Up Approach)

 

//down-up approach for normal BTree(not a BST)
//there's no parent pointer
Node *LCA(Node *pRoot, Node *p, Node *q)
{
    if (!pRoot)
        return NULL;

    if (pRoot == p || pRoot == q)
        return pRoot;

    Node *L = LCA(pRoot->pLeft, p, q);
    Node *R = LCA(pRoot->pRight, p, q);

    if (L && R)
        return pRoot;

    return L ? L : R;
}

 

 

 

 

 

EOF

posted on 2012-12-08 17:51  kkmm  阅读(168)  评论(0编辑  收藏  举报