给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
输入:root = [2,1,3] 输出:true
解题思路:
主要还是树的遍历,递归调用的变种,难点在于思考上下级节点的关系
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def recurr(node,low,high):
if not node:
return True
if node.val <= low or node.val >= high:
return False
if not recurr(node.left, low, node.val):
return False
if not recurr(node.right, node.val, high):
return False
return True
return recurr(root, -inf, inf)
return recurr(root,low=root.val,high=root.val)