[tag] bst, recursion
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def dfs(cur, small, large):
if not cur:
return True
if not (small < cur.val < large):
return False
else:
return dfs(cur.left, small, cur.val) and dfs(cur.right, cur.val, large)
return dfs(root, float('-inf'), float('inf'))
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def inorder(cur):
if not cur:
return True
if not inorder(cur.left):
return False
if self.prev and self.prev.val >= cur.val:
return False
self.prev = cur
return inorder(cur.right)
self.prev = None
return inorder(root)