smj007

Untitled

Jun 20th, 2022
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. class Solution:
  2.     def isValidBST(self, root: Optional[TreeNode]) -> bool:
  3.        
  4.         return self.helper(root, -math.inf, math.inf)
  5.    
  6.    
  7.     def helper(self, root, minVal, maxVal):
  8.        
  9.         if not root:
  10.             return True
  11.        
  12.         # ensure the root is in the prescribed range
  13.         if not (minVal < root.val < maxVal):
  14.             return False
  15.        
  16.         # check condition for left subtree
  17.         left = self.helper(root.left, minVal, root.val)
  18.        
  19.         # check condition for right subtree
  20.         right = self.helper(root.right, root.val, maxVal)
  21.        
  22.         # return if both the subtree condition are satisfied
  23.         return left and right
  24.        
Advertisement
Add Comment
Please, Sign In to add comment