码迷,mamicode.com
首页 > 其他好文 > 详细

235 Lowest Common Ancestor of a Binary Tree

时间:2015-07-13 07:48:45      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

题目 235 Lowest Common Ancestor of a Binary 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)

 

235 Lowest Common Ancestor of a Binary Tree

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4641982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!