二叉搜索树的性质就是左子树中所有节点值小于当前根节点,右子树中所有节点值大于当前根节点
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
min1 = TreeNode(float('-inf'))
max1 = TreeNode(float('inf'))
def helper(root,min1,max1):
if not root:
return True
if min1 and root.val <= min1.val: #右子树中节点的值不能小于root.val
return False
if max1 and root.val >= max1.val: #左子树中节点的值不能大于root.val
return False
return helper(root.left,min1,root) and helper(root.right,root,max1) #注意这里的root也会随着root的改变而改变
return helper(root,min1,max1)
根据中序遍历是有序的性质,解答问题
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
stack = []
inorder = float("-inf")
while stack or root:
if root:
stack.append(root)
root = root.left
else:
tmp = stack.pop()
if tmp.val <= inorder: #中序遍历 记录前一个弹出的节点的值,根据升序原则,后面弹出的值要大于前面的,否则返回False
return False
inorder = tmp.val
root = tmp.right
return True