方法一
这种方法是利用递归的思想,lower < node.val < upper
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root:
return True
def isBST(node,lower,upper):
if lower is not None and node.val <= lower:
return False
if upper is not None and node.val >= upper:
return False
left = isBST(node.left, lower, node.val) if node.left else True
if left :
right = isBST(node.right,node.val, upper) if node.right else True
return right
else:
return False
return isBST(root,None,None)
方法二
中序遍历的方式(非递归)
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack,inorder = [],float("-inf")
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if root.val <= inorder:
return False
inorder = root.val
root = root.right
return True