236求最近公共祖先

该博客介绍了一个二叉树问题,即寻找给定两个节点的最低公共祖先(Lowest Common Ancestor, LCA)。解决方案通过递归地在二叉树的左右子树中搜索目标节点,当在某一路线上找到目标节点时返回其父节点,最终得到LCA节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root is None or root is q or root is p:
            return root
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)

        
        # 兵分两路,搜查而已,那一条路上找到了有价值的p或者q就向上汇报
        # 没一个节点都会汇总情况,没有找到有价值的那一路就不用向上汇报了
        if l is not None and r is not None:
            return root
        elif l is not None and r is None:
            return l
        elif l is None and r is not None:
            return r
        else:
            return None
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值