卖萌的弱渣

I am stupid, I am hungry.

Lowest Common Ancestor of BST

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).”

1
2
3
4
5
6
7
    _______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.

Solution

递归寻找两个带查询LCA的节点p和q,当找到后,返回给它们的父亲。如果某个节点的左右子树分别包括这两个节点,那么这个节点必然是所求的解,返回该节点。否则,返回左或者右子树

(Lowest-Common-Ancestor-of-BST.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """

        if root == None:
            return None
        # 找到目标之一
        if root.val == p.val or root.val == q.val:
            return root

        leftTree = self.lowestCommonAncestor(root.left,p,q)
        rightTree = self.lowestCommonAncestor(root.right,p,q)

        if leftTree != None and rightTree != None:
            return root
        if leftTree != None:
            return leftTree
        if rightTree != None:
            return rightTree
        return None