A Python solution

  • 0
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        def isValidBST(self, root):
            :type root: TreeNode
            :rtype: bool
            def isValidBSTHelper(root, lower, upper):
                if root is None:
                    return True
                middle = root.val
                if middle <= lower or middle >= upper:
                    return False
                if root.left is not None:
                    left_valid = isValidBSTHelper(root.left, lower, middle)
                    if not left_valid:
                        return False
                if root.right is not None:
                    right_valid = isValidBSTHelper(root.right, middle, upper)
                    if not right_valid:
                        return False
                return True
            return isValidBSTHelper(root, float('-inf'), float('inf'))

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.