• LeetCode98. Validate Binary Search Tree


    题目:

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

    Assume a 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:
        2
       / 
      1   3
    Output: true
    

    Example 2:

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

    思路:

    要判定一棵树是二叉搜索树,需要判定两点,一个是当前节点的值小于右子树的最小值,大于左子树的最大值;一个是其左右子树仍满足这个性质。

    这与“判定一棵树是否是平衡二叉树”问题类似,于是想到一种自底向上的解法,依次判定左右子树是否为二叉搜素树,并向上传递左右子树的最小值、最大值及是否为二叉搜索树。代码如下:

    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if not root:
                return True
            _i, _j, res = self.checkValid(root)
            return res
    
        def checkValid(self, root):
            max_val, min_val = root.val, root.val
            if root.left:
                left_max, left_min, left_res = self.checkValid(root.left)
                if not left_res or left_max >= root.val:
                    return 0, 0, False
                min_val = left_min
            if root.right:
                right_max, right_min, right_res = self.checkValid(root.right)
                if not right_res or right_min <= root.val:
                    return 0, 0, False
                max_val = right_max
            return max_val, min_val, True

    但这种传递显得比较乱,要写的代码比较长,因此使用另一个方式,自顶向下的判断,并将判断结果自底向上传递。代码如下,会简洁一些:

    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            return self.checkValid(root, float('-inf'), float('+inf'))
    
        def checkValid(self, root, min_val, max_val):
            if not root:
                return True
            if root.val <= min_val or root.val >= max_val:
                return False
            return (self.checkValid(root.left, min_val, root.val) and self.checkValid(root.right, root.val, max_val))

    另, float('+inf')表示正无穷的这种用法也比较有趣。

  • 相关阅读:
    the selected directory is not a TomEE home
    java 获取当前年份 月份,当月第一天和最后一天
    java jwt工具类,生成和解析token
    Thymeleaf嵌套循环,每次循环显示固定数量
    oracle 非正常关机 错误1033解决办法
    webService简单记录
    好用的json工具
    org.apache.ws.commons.schema.XmlSchemaForm.getValue()Ljava/lang/String;
    webservice获取ip地址
    JSP(一)
  • 原文地址:https://www.cnblogs.com/plank/p/9129412.html
Copyright © 2020-2023  润新知