Leetcode 98. 验证二叉搜索树 / python实现

题目

在这里插入图片描述

代码实现

"""
解法1:利用二叉树的性质:中序遍历的结果为升序序列(无重复数字的)
"""
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        r = []
        def order(root):
            if not root:
                return
            order(root.left)
            r.append(root.val)
            order(root.right)
        order(root)
        t = sorted(r)
        return r == t and len(set(r)) == len(r)
"""
解法2:改进解法1,不利用额外空间存储
"""
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        self.pre = float("-inf")
        def order(root):
            if not root:
                return True
            if not order(root.left):
                return False
            if root.val <= self.pre:
                return False
            self.pre = root.val
            if not order(root.right):
                return False
            return True
        return order(root)
"""
解法3:递归
"""
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        if not root:
            return True
        if self.findMin(root.right) > root.val and self.findMax(root.left) < root.val:
            return self.isValidBST(root.left) and self.isValidBST(root.right)
        return False
    
    # 找到当前树的最小值,即根的左子树的最右边的结点(不一定是叶子结点)
    def findMin(self, r):
        # 空树也是符合条件的二叉搜索树
        min = float("inf")
        while r:
            min = r.val
            r = r.left
        return min

    # 最大值,即右子树的最左边的结点
    def findMax(self, r):
        max = float("-inf")
        while r:
            max = r.val
            r = r.right
        return max
"""
解法4:递归,学习官方的解法。
"""
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        return self.check(root, float("-inf"), float("inf"))

    def check(self, r, low, high):
        if not r:
            return True
        if r.val <= low or r.val >= high:
            return False
        return self.check(r.left, low, r.val) and self.check(r.right, r.val, high)

おすすめ

転載: blog.csdn.net/qq_42711381/article/details/115740325