首页 > 其他分享 >98. 验证二叉搜索树

98. 验证二叉搜索树

时间:2023-01-29 11:22:33浏览次数:27  
标签:right val 验证 max min 二叉 98 root left

问题描述

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

解题思路

二叉搜索树的性质是:root节点要大于左子树的最大值,小于右子树的最小值。

同时,对上层,也要更新本层的最大值和最小值以供继续递归。

代码

# 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:
        flag = True
        def dfs(root):
            if root is None:
                return None, None
            left_min, left_max = dfs(root.left)
            right_min, right_max = dfs(root.right)
            nonlocal flag
            if not flag:
                return None, None
            mins, maxs = root.val, root.val
            if left_max and left_max < root.val:
                mins = left_max
            elif left_max:
                flag = False
            if right_min and right_min > root.val:
                maxs = right_min
            elif right_min:
                flag = False
            if left_min:
                mins = min(left_min, mins)
            if right_max:
                maxs = max(maxs, right_max)
            return mins, maxs
        dfs(root)
        return flag

 

标签:right,val,验证,max,min,二叉,98,root,left
From: https://www.cnblogs.com/bjfu-vth/p/17072116.html

相关文章

  • 美国亚马逊家用电器UL​​认证​​家用厨房绞肉机UL982测试报告办理
    家用绞肉机的需求变化:作为满足家庭烹饪基本实需求的工具类产品,绞肉机帮助经常在家烹饪或偶尔下厨的人群节省时间,解放双手或减轻劳动力。从需求角度来看:一是自动化代替手动操......
  • node借助jsonwebtoken生成token以及验证token是否过期
    生成token使用jsonwebtoken插件我当时使用的版本"jsonwebtoken":"^9.0.0",cnpmijsonwebtoken-S登录后生成token//routes/index.js文件varexpress=require(......
  • 257. 二叉树的所有路径
    问题描述https://leetcode.cn/problems/binary-tree-paths/description/解题思路叶子结点时,添加到结果序列即可。代码#Definitionforabinarytreenode.#class......
  • 226. 反转二叉树
    问题描述https://leetcode.cn/problems/invert-binary-tree/description/解题思路没啥好说的,python的交换简单极了。代码#Definitionforabinarytreenode.#cl......
  • 144. 二叉树的前序遍历
    问题描述https://leetcode.cn/problems/binary-tree-preorder-traversal/description/解题思路二叉树的先序遍历,没啥好说的。中-左-右。先序中序后序说的是中在哪里。......
  • 145. 二叉树的后序遍历
    问题描述https://leetcode.cn/problems/binary-tree-postorder-traversal/description/解题思路这个题和先序一样,没啥好说的。代码#Definitionforabinarytreen......
  • 翻转二叉树
    /***注意:left/right值若没有显示设置为null,值即为undefined*在调用二叉树前、中、后序遍历方法时,由于参数设置了默认值(tree)*所以进入了死循环*/consttree={......
  • 111. 二叉树的最小深度
    问题描述https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/解题思路这个题目不难,但对退出条件要求高。经过对题意的分析,我们对于root为None的......
  • 110. 平衡二叉树
    问题描述https://leetcode.cn/problems/balanced-binary-tree/description/解题思路这题一开始朴素的思路就是,对于每个节点,都计算其是不是平衡二叉树。计算平衡二叉树......
  • 104. 二叉树的最大深度
    问题描述https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/解题思路二叉树的最大深度,等于左子树的深度和右子树深度的较大值加1(即本层深度).代......