LeetCode#235 Lowest Common Ancestor of a Binary Search Tree

Problem Definition:

  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) 排序,确保p<=q;

  3) 如果根节点值大于p而小于q,则p和q分别在根节点的左右子树,根节点就是要找的最低公共祖先,返回它;

  4) 如果根节点值大于较大的q,则p和q都在根节点的左子树,令根节点左子节点为新的根节点;如果根节点值小于较小的p,则p和q都在根节点的右子树

    另根节点右子节点为新的根节点;

  5)递归地进行1)-->4).

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @param {TreeNode} p
    # @param {TreeNode} q
    # @return {TreeNode}
    def lowestCommonAncestor(self, root, p, q):
        if (root.val==p.val) or (root.val==q.val):
            return root
        if p.val>q.val:
            p,q=q,p
        if p.val<root.val and root.val<q.val:
            return root
        if root.val>q.val:
            root=root.left
        if root.val<p.val:
            root=root.right
        if root!=None:
            return self.lowestCommonAncestor(root, p, q)
        
            

  

原文地址:https://www.cnblogs.com/acetseng/p/4648741.html