leetcode(253):Lowest Common Ancestor of a Binary Search Tree

题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

题目分析:这个题最主要得还是要利用二叉搜索树的性质,这个是最重要的性质,在做二叉搜索树的时候,这个是最重要的,需要时时的牢记。
当不返回值的时候,认为是返回None。

python代码实现:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root and p and q:
            if root.val >= min(p.val, q.val) and root.val <= max(p.val, q.val):
                return root
            if root.val > min(p.val, q.val):
                return self.lowestCommonAncestor(root.left, p, q)
            if root.val < max(p.val, q.val):
                return self.lowestCommonAncestor(root.right, p, q)

让我们来看看大佬们的奇思妙想把,哈哈,学习永无止尽。

class Solution:

def lowestCommonAncestor(self, root, p, q):
    while root:
        if root.val > p.val and root.val > q.val:
            root = root.left
        elif root.val < p.val and root.val < q.val:
            root = root.right
        else:
            return root

跟大佬们的思路是一样的,只是实现的方式不一样,大佬们是从简单的往难的排除,难的那部分包含种类比较多,但可以综合起来对其一起来进行处理,所以,程序还是很简洁。并且,不是采用递归的做法,而是采用迭代的办法,利用root的变化来进行迭代,我采用的是递归的手段来进行处理。所以应该是实现手法不同,但思想是一致的。

猜你喜欢

转载自blog.csdn.net/angela2016/article/details/79586690