zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):098 Validate Binary Search Tree

    题目来源


    https://leetcode.com/problems/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.

    题意分析


    Input:二叉树

    Output:boolean值

    Conditions:检验一个二叉树是不是有效的二叉搜索树


    题目思路


    注意到,每层的最大最小约束都是不一样的,所以采用dfs的思想,不断更新最大最小值。在python中,数字可以取很大,要设大一点。


    AC代码(Python)

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution(object):
     9     def validBST(self, root, min, max):
    10         if root == None:
    11             return True
    12         if root.val <= min or root.val >= max:
    13             return False
    14         return self.validBST(root.left, min, root.val) and self.validBST(root.right, root.val, max)
    15     def isValidBST(self, root):
    16         """
    17         :type root: TreeNode
    18         :rtype: bool
    19         """
    20         return self.validBST(root, -21474836480, 21474836470)
    21         
  • 相关阅读:
    重构drf后的环境变量配置
    分离的前后台交互
    虚拟环境的搭建
    Python
    Python
    Python
    Python操作MongoDb数据库
    Python操作SQLite/MySQL/LMDB
    数据库-如何创建SQL Server身份验证用户
    Python
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5456112.html
Copyright © 2011-2022 走看看