zoukankan      html  css  js  c++  java
  • [LeetCode in Python] 98 (M) validate binary search tree 验证二叉搜索树

    题目

    https://leetcode-cn.com/problems/validate-binary-search-tree/

    给定一个二叉树,判断其是否是一个有效的二叉搜索树。
    假设一个二叉搜索树具有如下特征:

    节点的左子树只包含小于当前节点的数。
    节点的右子树只包含大于当前节点的数。
    所有左子树和右子树自身必须也是二叉搜索树。

    示例 1:

    输入:

        2
       / 
      1   3
    

    输出: true

    示例 2:

    输入:

        5
       / 
      1   4
         / 
        3   6
    

    输出: false

    解释: 输入为: [5,1,4,null,null,3,6]。
      根节点的值为 5 ,但是其右子节点值为 4 。

    解题思路

    • DFS
    • 仅仅查看当前节点和左右子树的节点还不够
    • 还需要维持一个最小最大的极值来判断

    代码

    # 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:
    
            def dfs(node, min_node, max_node):
                if not node: return True
    
                # - check node
                if min_node and (node.val <= min_node.val): return False
                if max_node and (node.val >= max_node.val): return False
    
                # - dfs left and right branch
                if node.left and (not dfs(node.left, min_node, node)): return False
                if node.right and (not dfs(node.right, node, max_node)): return False
    
                return True
    
            return dfs(root, None, None)
    
  • 相关阅读:
    微信小程序退款【证书的使用】
    生成随机位数的UUID
    弹出层-layui
    load加载层-layui
    form-layui
    table-layui
    下拉列表模仿placeholder效果
    .net core 2.0 Unable to convert MySQL date/time to System.DateTime
    .net core Include问题
    .net core 2.0 配置Session
  • 原文地址:https://www.cnblogs.com/journeyonmyway/p/12749395.html
Copyright © 2011-2022 走看看