Skip to content

235 lowest common ancestor of a binary search tree

235. Lowest Common Ancestor of a Binary Search Tree

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

难度 : Easy

  • 两个node,一个大于root,一个小于root,那么必定root两边,共同的ancestor是root,同时再考虑同为空的状况
  • 两个node,都比node小,到左边去寻找,那么先找到那个必定是common ancestor
  • 两个node,都比node大,类似....

AC解法

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root == None or root == p or root == q:
            return root
        elif p.val < root.val < q.val or q.val < root.val < p.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)


回到顶部