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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章