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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章