LeetCode 98. Validate Binary Search Tree - 二叉搜索树(Binary Search Tree)系列题3

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [2,1,3]
Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

题目要求验证一棵二叉树是否为二叉搜索树(BST: Binary Search Tree)。首先要明白二叉搜索树的特点,对于一个节点,其左子树的所有节点值不能大于等于该节点值,其右子树的所有节点值不能小于等于该节点值,还有就是左右子树也都必须是二叉搜索树。

根据以上分析,很容易想到用递归法。本题可以有两种递归法,分别是自顶向下和自底向上。

解法一:自顶向下递归就是从根节点开始判断每个节点是否满足二叉搜索树的要求。对于树里的一个节点node,如果它的值的有效范围是[low, high],那么它的左子节点的有效范围是[low, node.val],右子节点的有效范围是[node.val, high]。对于根节点,范围没有限制可以是[INT_MIN, INT_MAX],按此规则从根节点开始依次判断每个节点,如果所有节点都满足要求则是一棵有效二叉搜索树。

# 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: Optional[TreeNode]) -> bool:
        def helper(root, low, high):
            if not root:
                return True
            
            if (root.val <= low) or (root.val >= high):
                return False
            
            return helper(root.left, low, root.val) and helper(root.right, root.val, high)
        
        return helper(root, -sys.maxsize, sys.maxsize)

 解法二,自底向上递归法就是通过递归判断一个节点的左右子树是否为有效二叉搜索树,同时向上返回子树的最小值和最大值,节点值一定要大于其左子树的最大值,一定要小于右子树的最小值。对于一个空节点,由于其肯定有效,所以空节点返回的最大值是无穷小,最小值是无穷大,这样空节点返回到上层永远有效。

# 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: Optional[TreeNode]) -> bool:
        def helper(root):
            if not root:
                return True, sys.maxsize, -sys.maxsize
            lvalid, lmin, lmax = helper(root.left)
            rvalid, rmin, rmax = helper(root.right)
            if lvalid and rvalid and lmax < root.val and root.val < rmin:
                return True, min(lmin, root.val), max(root.val, rmax)
            
            return False, None, None
        
        return helper(root)[0]
        
        return True

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值