美文网首页
235. Lowest Common Ancestor of a

235. Lowest Common Ancestor of a

作者: GoDeep | 来源:发表于2018-05-02 16:03 被阅读0次
image.png

如果树是查找树,可以优化

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        a1,a2 = root.val-p.val, root.val-q.val
        if a1*a2<=0: return root
        elif a1<0: return self.lowestCommonAncestor(root.right, p, q)
        else: return self.lowestCommonAncestor(root.left, p, q)
        

相关文章

网友评论

      本文标题:235. Lowest Common Ancestor of a

      本文链接:https://www.haomeiwen.com/subject/xcecrftx.html