这个题目是一个十分经典的题目,需要我们验证一个二叉搜索树是否是有效的。如果这是一个有效的二叉搜索树,那么一定需要满足这样的条件:

每一棵subtree的所有left subtree都比root要小,每一棵right subtree都要比root要大,因此我们可以写出这样的代码:

# 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 BFS(root, left, right):
            if root is None:
                return True
            if left < root.val < right:
                #卡在中间进行判断
                return BFS(root.left, left, root.val) and BFS(root.right, root.val, right)
            else:
                return False

        return BFS(root, -float('inf'), float('inf'))

得解

相关文章:

  • 2021-06-19
  • 2021-12-22
  • 2021-09-08
  • 2022-02-19
猜你喜欢
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-11
  • 2021-08-23
  • 2021-06-26
相关资源
相似解决方案