LeetCode----Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

分析:

此時的二叉樹爲普通的二叉樹,無法像BST樹一樣可以利用BST的特性進行求解了。

思路:遞歸在root結點的左右子樹中搜索p和q,如果兩邊都搜索成功,說明root即爲LCA,否則,如果p和q爲上下級關係時,此時只能搜索到p或者q(因爲一旦搜索成功即停止搜索,遞歸返回了),返回後的結點p或者q即爲要找的LCA。


代碼:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root or root == p or root == q:
            return root
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
        # 如果l和r都存在,說明root是LCA;否則,返回的是隻會是l或者r,表示p和q爲上下級關係
        return root if l and r else (l if l else r)
發佈了143 篇原創文章 · 獲贊 59 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章