如果左子树的值小于根的值并且右子树的值大于根的值,并进行递归,成立则为二叉搜索树,否则则不是。
class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
def isValidBST(self,root):
min=max=None
return self.helper(root,min,max)
def helper(self,root,min,max):
if root is None:
return True
if min is not None and root.val<=min:
return False
if max is not None and root.val>=max:
return False
if self.helper(root.left,min,root.val) and self.helper(root.right,root.val,max):
return True
else:
return False