LintCode 474 [Lowest Common Ancestor II]

原題

給一棵二叉樹和二叉樹中的兩個節(jié)點,找到這兩個節(jié)點的最近公共祖先LCA。

兩個節(jié)點的最近公共祖先,是指兩個節(jié)點的所有父親節(jié)點中(包括這兩個節(jié)點),離這兩個節(jié)點最近的公共的節(jié)點。

每個節(jié)點除了左右兒子指針以外,還包含一個父親指針parent,指向自己的父親。

對于下面的這棵二叉樹

  4
 / \
3   7
   / \
  5   6

LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7

解題思路

  • 根據(jù)p,一路向上找到所有的parent,得到一個list
  • 根據(jù)q,一路向上找到所有的parent,得到一個list
  • 從左向右看兩個list,最先一樣的node即為公共祖先

完整代碼

"""
Definition of ParentTreeNode:
class ParentTreeNode:
    def __init__(self, val):
        this.val = val
        this.parent, this.left, this.right = None, None, None
"""
class Solution:
    """
    @param root: The root of the tree
    @param A and B: Two node in the tree
    @return: The lowest common ancestor of A and B
    """ 
    def lowestCommonAncestorII(self, root, p, q):
        list = []
        while p:
            list.append(p)
            p = p.parent
        
        while q:
            if q in list:
                return q
            q = q.parent
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容