美文网首页
Lowest Common Ancestor II

Lowest Common Ancestor II

作者: 一枚煎餅 | 来源:发表于2016-09-18 13:57 被阅读0次
    Lowest Common Ancestor II.png

    解題思路 :

    既然有給 parent 的指針 先把 A 點跟 A所有 parents 都存入 set (搜尋快速 O(1)) 接著在檢查 B 點跟 B 的所有 parents 有沒有出現在剛剛存的清單之中

    C++ code :

    <pre><code>
    /**

    • Definition of ParentTreeNode:
    • class ParentTreeNode {
    • public:
    • int val;
      
    • ParentTreeNode *parent, *left, *right;
      
    • }
      */

    class Solution {

    public:

    /**
     * @param root: The root of the tree
     * @param A, B: Two node in the tree
     * @return: The lowest common ancestor of A and B
     */
    ParentTreeNode *lowestCommonAncestorII(ParentTreeNode *root,
                                           ParentTreeNode *A,
                                           ParentTreeNode *B) {
        // Write your code here
        unordered_set<ParentTreeNode*> checked;
        while(A){
            checked.insert(A);
            A = A->parent;
        }
        while(B)
        {
            if(checked.count(B)) return B;
            B = B->parent;
        }
    }
    

    };

    相关文章

      网友评论

          本文标题:Lowest Common Ancestor II

          本文链接:https://www.haomeiwen.com/subject/gbtgettx.html