Lowest Common Ancestor II

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

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 提問的智慧 How To Ask Questions The Smart Way Copyright © 2001...
    Albert陈凯阅读 7,436评论 0 8
  • 为何叫做 shell ? shell prompt(PS1) 与 Carriage Return(CR) 的关系?...
    Zero___阅读 8,407评论 3 49
  • 原来我非不快乐 始2016.6.27 聽說,能到達金字塔頂端的只有兩種動物,一是雄鷹,靠著自己的...
    _行走中的蝸牛_阅读 5,403评论 1 8
  • 【杯子技巧】 和對方的交情還屬於曖昧不清的階段,正確掌握和對方的距離感,是很困難的事。 最可怕的是,你覺得兩人的感...
    77733261dbff阅读 3,942评论 0 0
  • 当疲乏深入到骨髓,困倦席卷到全身,你想逃离喧嚣外界,拉上窗帘,裹上被子,塌陷在柔软的床上。可是越困顿,无睡意,静静...
    三步一叩首阅读 4,079评论 5 2