python - 二叉树的最近公共祖先

本文转自:https://blog.csdn.net/wenqiwenqi123/article/details/79952043

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

 注意事项

假设给出的两个节点都在树中存在

LCA(最近公共父节点)问题是二叉树里很经典的问题了,若是树的结构中有parent指针的话那这一题就很容易了,若没有的话就需要想一想了。

依然用到了分治法的思想,想一想,若是对于一个树结点,在左子树中找到了A,在右子树中找到了B,那说明此结点是公共节点

详细思想写在代码注释里了(对于源代码,本文的代码稍微有点修改)

 

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
 
 
class Solution:
    """
       @param: root: The root of the binary search tree.
       @param: A: A TreeNode in a Binary.
       @param: B: A TreeNode in a Binary.
       @return: Return the least common ancestor(LCA) of the two nodes.
       """
 
    def lowestCommonAncestor(self, root, A, B):
        # A&B=>LCA
        # !A&!B=>None
        # A&!B=>A
        # B&!A=>B
        if(root is None or root==A or root==B):
            return root        #若root为空或者root为A或者root为B,说明找到了A和B其中一个
        left=self.lowestCommonAncestor(root.left,A,B)
        right=self.lowestCommonAncestor(root.right,A,B)
        if left  and right :
            return root      #若左子树找到了A,右子树找到了B,说明此时的root就是公共祖先
        if not left :    #若左子树是none右子树不是,说明右子树找到了A或B
            return right
        if not right :   #同理
            return left
        return None
 
 
 
a=Tree = TreeNode(2)
b=Tree.left = TreeNode(1)
c=Tree.right = TreeNode(3)
d=b.left=TreeNode(4)
s = Solution()
print(s.lowestCommonAncestor(a,b,d).val)

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值