欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

程序员文章站 2022-07-14 14:11:19
...

题目

LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

思路

因为是BST,所以可以判断root和p、q的大小关系。

代码

# 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 not root or root == p or root == q: return root
        if root.val < p.val and root.val < q.val: return self.lowestCommonAncestor(root.right, p, q)
        if root.val > p.val and root.val > q.val: return self.lowestCommonAncestor(root.left, p, q)
        return root