题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param root TreeNode类 
# @param p int整型 
# @param q int整型 
# @return int整型
#
class Solution:
    def __init__(self) -> None:
        self.minc = 0
        self.minanc = 0

    def findp(self,root,p):
        if root is None:
            return False
        else:
            if root.val==p:
                return True
            else:
                leftg = self.findp(root.left,p)
                rightg = self.findp(root.right,p)
                return leftg or rightg

    def dps(self, root, p,q, depth):
        if root is None:
                return 0
        else:
            getp = self.findp(root,p)
            getq = self.findp(root,q)
            if getp and getq:
                if depth>self.minc:
                    self.minc = depth
                    self.minanc = root.val
            leftg = self.dps(root.left,p,q,depth+1)
            rightg = self.dps(root.right,p,q,depth+1)   
            return 0

            
    def lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int:
        # write code here
        self.dps(root,p,q,1)
        return self.minanc

全部评论

相关推荐

05-16 11:16
已编辑
东华理工大学 Java
牛客73769814...:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
牛客创作赏金赛
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务