zoukankan      html  css  js  c++  java
  • [Leetcode]@python 98. 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.

    题目大意

    给定一棵二叉树,判断这棵二叉树是否有效地二叉搜索树

    解题思路

    递归:棵树是二叉查找树,那么左子树的节点值一定处于(负无穷,root.val)这个范围内,右子树的节点值一定处于(root.val,正无穷)这个范围内。(注意边界值,负无穷和正无穷换成浮点型的极值)

    代码

    # Definition for a binary tree node.
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    
    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            return self.isValid(root, -2147483648.1, 2147483647.1)
    
        def isValid(self, root, min, max):
            if not root:
                return True
            if root.val <= min or root.val >= max:
                return False
    
            return self.isValid(root.left, min, root.val) and self.isValid(root.right, root.val, max)
    
  • 相关阅读:
    象棋人工智能的实现
    cocos2dx实现象棋之运动
    python基础实战之猜年龄游戏
    python流程控制if判断与循环(for、while)
    python基本算术运算符
    python格式化输出的三种方式
    python解压缩
    python集合
    python元组
    python布尔类型
  • 原文地址:https://www.cnblogs.com/slurm/p/5221590.html
Copyright © 2011-2022 走看看