leetcode -- Lowest Common Ancestor of a Binary Search Tree -- 简单递归,掌握思想

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

ref: http://bookshadow.com/weblog/2015/07/11/leetcode-lowest-common-ancestor-binary-search-tree/

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """

        if (q.val - root.val) * (p.val - root.val) <= 0:
            return root.val
        elif q.val > root.val :
            return self.lowestCommonAncestor(root.right, p, q)
        else:
            return self.lowestCommonAncestor(root.left, p, q)

你可能感兴趣的:(LeetCode)