Leetcode 700. Search in a Binary Search Tree [Python]

基本上就是LCA的写法。

class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:return None
        if root.val == val:return root
        left = self.searchBST(root.left, val)
        right = self.searchBST(root.right, val)
        if left and right:return root
        if left:return left#如果是保证有解的LCA,这里就是return left if left else right,然后结束
        if right:return right
        return None

你可能感兴趣的:(Leetcode学习记录,leetcode,python,动态规划)