zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Quagga How to use Quagga
    Quagga Case 4
    Quagga Case 3
    Quagga Case 2
    Quagga Routing Suite
    quagga
    quagga 的原理解析 zebra原理解析
    zebra线程管理源码简析
    【习题 4-8 UVA
    【习题 4-7 UVA
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2809151.html
Copyright © 2011-2022 走看看