My Solution to Lowest Common Ancestor of a Binary Tree Part II (Node has parent Pointer)

 

struct Node{
    int value;
    Node *pLeft;
    Node *pRight;
    Node *pParent;
};

//BTree(not a BST)
//both has parent pointer
Node *LCA(Node *p, Node *q)                    //这里的p q为NULL的检测融入到了代码当中
{
    int pDepth = 0;
    int qDepth = 0;

    Node *walker = p;
    while (!walker)
    {
        walker = walker->pParent;
        pDepth++;
    }

    walker = q;
    while (!walker)
    {
        walker = walker->pParent;
        qDepth++;
    }

    int depthDiff =    0;                        //高度之差
    if (pDepth > qDepth)
    {
        swap(pDepth, qDepth);
        swap(p ,q);
    }
    depthDiff = qDepth - pDepth;

    while (depthDiff-- > 0)
        q = q->pParent;

    while (p && q)
    {
        if (p == q)
            return p;
        p = p->pParent;
        q = q->pParent;
    }

    return NULL;                            //p q不在同一棵树里,这种情况也要考虑
}

 

 

 

 

 

 

EOF

posted on 2012-12-08 19:10  kkmm  阅读(196)  评论(0编辑  收藏  举报