【leetcode】98:验证是否是二叉树

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

每一棵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'))

得解

posted @ 2021-04-07 14:46  Geeksongs  阅读(44)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.