236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

Description

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Idea

题为找到两个node的公共祖先。而且这两个给定的node p和q在tree中一定存在且tree里的任意node都是unique value的。
我们可以把题目分为以下几种情况:

  • p和q有一个等于root:LCA为root
  • p和q分别在左右子树中:LCA为root
  • p和q同在左子树中:去左子树继续找LCA
  • p和q同在右子树中:去右子树继续找LCA

in general,我们可以分别去左右子树找p和q并return第一个遇到的node。如果p和q在同一侧则第一个遇到的node为LCA, 如果不在同一侧 - 左右子树均能找到第一个遇到的node,则root 为LCA。

Code

下面展示一些 内联代码片

    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return None
        # 第一种情况, p和q中有一个是root则root为公共祖先
        if root == p or root == q:
            return root
        # 分别去左右子树寻找p和q, 并return找到的第一个node
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        # 如果left和right都能找到一个node,则root为LCA
        if left and right:
            return root
        # 如果left或者right只有一个return了值那么那个return的值即为LCA
        if left:
            return left
        return right

Notes

通过设计LCA函数为return第一个遇到的node,简化了代码:使同一段代码即可以找到LCA也可以判断p q是否在同一侧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值