leetcode98 验证二叉搜索树

leetcode98 验证二叉搜索树_第1张图片
leetcode98 验证二叉搜索树_第2张图片
思路一:对数中序遍历,检查得到的遍历是否为升序

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        if not root:
            return True
        res = []
        def helper(root):   #中序遍历
            if not root:
                return
            helper(root.left)
            res.append(root.val)
            helper(root.right)
        helper(root)
        for i in range(1,len(res)):
            if res[i] <= res[i-1]:
                return False
        return True

思路二:用递归法实现。首先将结点的值与上界和下界(如果有)比较。然后,对左子树和右子树递归进行该过程。
leetcode98 验证二叉搜索树_第3张图片
具体过程:
leetcode98 验证二叉搜索树_第4张图片
leetcode98 验证二叉搜索树_第5张图片
leetcode98 验证二叉搜索树_第6张图片

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        lower = float('-inf')
        upper = float('inf')
        def helper(root,lower,upper):
            if not root:
                return True
            val = root.val
            if val <= lower or val >= upper:
                return False
            return helper(root.left,lower,val) and helper(root.right,val,upper)
            
        return helper(root,lower,upper)

你可能感兴趣的:(leetcode,刷题)