美文网首页
02_验证二叉搜索树

02_验证二叉搜索树

作者: butters001 | 来源:发表于2019-11-09 13:04 被阅读0次
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        res = []

        def helper(root):
            if not root:
                return None
            helper(root.left)
            res.append(root.val)
            helper(root.right)

        helper(root)
        return res == sorted(res) and len(set(res)) == len(res)


class Solution2(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.pre = None

        def isBST(root):
            if not root:
                return True

            if not isBST(root.left):
                return False

            if self.pre and self.pre.val >= root.val:
                return False

            self.pre = root

            return isBST(root.right)

        return isBST(root)


class Solution3(object):

    def validBST(self, root, small, large):
        if root is None:
            return True
        if small >= root.val or large <= root.val:
            return False
        return self.validBST(
            root.left, small, root.val) and self.validBST(
            root.right, root.val, large)

    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.validBST(root, -2 ** 32, 2 ** 32 - 1)

相关文章

网友评论

      本文标题:02_验证二叉搜索树

      本文链接:https://www.haomeiwen.com/subject/qtxnbctx.html