Leetcode 1650. Lowest Common Ancestor of a Binary Tree III [Python]

这篇博客探讨了如何在给定的二叉树结构中找到两个节点的最近公共祖先。作者提供了两种解决方案,分别通过递归和利用父节点信息来实现。在亚麻(可能是LeetCode)的在线评估中,这个问题被考察过,但这里没有给出根节点。文章强调了正确使用父节点信息的重要性。
摘要由CSDN通过智能技术生成

传统办法,第30(29/31 pass)个TC会TLE。先写出来吧,找LCA的算法,亚麻的OA考过。不同的是亚麻OA给了root。

class Solution:
    def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
        root = self.findroot(p)
        print(root.val)
        res = self.helper(root, p, q)
        return res
    
    def findroot(self, node):
        while node.parent != None:
            node = node.parent
            self.findroot(node)
        return node
    
    def helper(self, root, p, q):
        if not root:return
        if root == p or root == q:return root
        left = self.helper(root.left, p, q)
        right = self.helper(root.right, p, q)
        if left and right:return root
        if left:return left
        if right:return right

接下来,好好使用parent。

class Solution:
    def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
        self.resp = []
        self.findroot(p, self.resp)
        while q:
            if q not in self.resp:
                q = q.parent
            else:
                return q
    
    def findroot(self, node, res):
        
        while node:
            res.append(node)
            node = node.parent
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值