# 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: TreeNode) -> bool:
return self.ValidBst(root)
def ValidBst(self, root, max_=float('inf'), min_=-float('inf')):
if root is None:
return True
if root.val >= max_ or root.val <= min_:
return False
if not self.ValidBst(root.left, max_=root.val, min_=min_):
return False
if not self.ValidBst(root.right, min_=root.val, max_=max_):
return False
return True
不想用中序遍历然后排序,采用上界和下界的方法,结果的传递不按照 expression1 and expression2...的方式,而是判断每个分支符合条件即可返回True,上界和下界的更新方式为值传递,仔细思考一下这种方式挺简便的。。。