Lowest Common Ancestor II

2016-09-18  本文已影响0人  一枚煎餅
Lowest Common Ancestor II.png

解題思路 :

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

C++ code :

<pre><code>
/**

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;
    }
}

};

上一篇下一篇

猜你喜欢

热点阅读