235 Lowest Common Ancestor of a Binary Search Tree

题目 235 Lowest Common Ancestor of a Binary Search Tree

因为是binary search tree,因此利用没个节点的值进行二分查找即可复杂度O(h)

class Solution:
    # @param {TreeNode} root
    # @param {TreeNode} p
    # @param {TreeNode} q
    # @return {TreeNode}
    def lowestCommonAncestor(self, root, p, q):
        if p.val > q.val:
            p,q = q,p
        if root.val in [p.val, q.val]:
            return root
        if p.val < root.val < q.val:
            return root
        elif p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        else:
            return self.lowestCommonAncestor(root.right, p, q)

 

posted @ 2015-07-13 07:38  dapanshe  阅读(106)  评论(0编辑  收藏  举报