LeetCode----Lowest Common Ancestor of a Binary Search Tree

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.


分析:

求出BST的LCA。考虑两种情况,一:p和q分别在root的左右子树中,root即为LCA,二:p和q为上下级关系,此时,递归遍历到root等于p或者等于q时,root即为LCA。


代码:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        # 如果某一个结点的左右子树中分别包含p,q,那么,该结点就是要找的结点
        # 或者,等于号说明,如果p和q是上下级关系的话,那么此时root也为LCA
        if p.val <= root.val <= q.val or q.val <= root.val <= p.val:
            return root
        else:
            # 否则的话,应该去这个根节点的子树中去查找。
            if p.val < root.val:
                # 去左子树中寻找
                return self.lowestCommonAncestor(root.left, p, q)
            else:
                # 去右子树中寻找
                return self.lowestCommonAncestor(root.right, p, q)

你可能感兴趣的:(LeetCode,python)