python --- LeetCode之 235. Lowest Common Ancestor of a Binary Search Tree

这篇博客介绍了如何在二叉搜索树中找到两个给定节点的最低公共祖先(LCA)。根据LCA的定义,它是同时是两个节点的最低节点。解题策略包括先判断给定点与根节点的关系,然后决定是在树的一侧搜索还是根节点即为答案。博客提供了详细的解题思路和非递归的代码实现。
摘要由CSDN通过智能技术生成

题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

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).”
题目理解:
找二叉搜索树中两节点的最近公共祖先。
方法:
思路与下面这个链接差不多,
https://blog.csdn.net/weixin_40283816/article/details/91346023
但可以先判断p、q和root的位置关系,如果在一侧,则去一侧寻找即可,如果在两侧,则root即为所求。
代码:

# 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 == None:
            return root
        if p.val < root.val > q.val:     # 均在左子树
            return self.lowestCommonAncestor(root.left, p, q)
        if p.val  > root.val < q.val:    # 均在右子树
            return self.lowestCommonAncestor(root.right, p, q)
        return root      # 在两侧,根结点即为所求

也可以采用非递归的方式:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        while root:
            if p.val < root.val > q.val:    # 在左子树寻找,直到有个节点满足p、q在其两侧
                root = root.left
            elif p.val  > root.val < q.val: # 在右子树寻找,直到有个节点满足p、q在其两侧
                root = root.right
            else:
                return root                 # p、q在两侧,返回该节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值