Skip to content

Instantly share code, notes, and snippets.

@izeigerman
Created May 21, 2019 17:48
Show Gist options
  • Save izeigerman/d8ebf99e636ecb07304d0eefa1da5237 to your computer and use it in GitHub Desktop.
Save izeigerman/d8ebf99e636ecb07304d0eefa1da5237 to your computer and use it in GitHub Desktop.
class Solution:
def _bst_helper(self, root, lower, upper):
if root is None:
return True
def within_contstraints(val):
if lower is None and upper is None:
return True
if lower is None:
return val < upper
if upper is None:
return val > lower
return lower < val < upper
this_val = root.val
left_val = root.left.val if root.left else None
right_val = root.right.val if root.right else None
if left_val is not None and (left_val >= this_val or not within_contstraints(left_val)):
return False
if right_val is not None and (right_val <= this_val or not within_contstraints(right_val)):
return False
return self._bst_helper(root.left, lower, this_val) and self._bst_helper(root.right, this_val, upper)
def isValidBST(self, root: TreeNode) -> bool:
return self._bst_helper(root, None, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment