98. 验证二叉搜索树 python 递归+中序遍历

https://leetcode-cn.com/problems/validate-binary-search-tree/
思路一:
中序遍历放在list里面,然后判断大小

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        output = []
        self.inOrder(root, output)
        
        for i in range(1, len(output)):
            if output[i-1] >= output[i]:
                return False

        return True

    def inOrder(self, root, output):
        if root is None:
            return
        
        self.inOrder(root.left, output)
        output.append(root.val)
        self.inOrder(root.right, output)

思路二:
递归

    def isValidBST(self, root: TreeNode) -> bool:
        def bst(root,min_=float('-inf'),max_=float('inf')):
            if not root:
                return True
            cur = root.val
            if min_>=cur or max_<=cur:
                return False
            if not bst(root.left,min_,cur):
                return False
            if not bst(root.right,cur,max_):
                return False
            return True
        return bst(root)

你可能感兴趣的:(数据结构,leetcode,算法)