leetcode -- Lowest Common Ancestor of a Binary Search Tree -- 简单递归,掌握思想

来源:互联网 发布:宁波用友软件代理商 编辑:程序博客网 时间:2024/06/03 19:01

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

ref: http://bookshadow.com/weblog/2015/07/11/leetcode-lowest-common-ancestor-binary-search-tree/

class Solution(object):    def lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        """        if (q.val - root.val) * (p.val - root.val) <= 0:            return root.val        elif q.val > root.val :            return self.lowestCommonAncestor(root.right, p, q)        else:            return self.lowestCommonAncestor(root.left, p, q)
0 0
原创粉丝点击