leetcode(39)-验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def isValidBST(self, root: TreeNode):
def isv(root, has2smaller,has2larger):
l,r = True,True
if root is not None:
if root.left is not None:
l = root.left.val<root.val and root.left.val>has2larger and root.left.val<has2smaller and isv(root.left,root.val,has2larger)
if root.right is not None:
r = root.right.val>root.val and root.right.val>has2larger and root.right.val<has2smaller and isv(root.right,has2smaller, root.val)
return l and r
else:
return True
return isv(root, 1<<32,-1<<32)

浙公网安备 33010602011771号