leetcode hot100 98. 验证二叉搜索树 medium 递归


二叉搜索树:

  1. 左子树所有节点值<根节点值<右子树所有节点值
  2. 左子树是二叉搜索树
  3. 右子树是二叉搜索树

  • 二叉搜索树的BST 定义:左子树 < 根 < 右子树。
  • 中序遍历顺序:左子树 → \rightarrow → 根 → \rightarrow →
    右子树。

即:中序遍历时,可以把二叉搜索树看成一个有序数组。

怎么判断一个数组是有序数组?比较相邻元素的大小即可。


时间复杂度: O ( N ) O(N) O(N)。每个节点访问一次。

空间复杂度: O ( H ) O(H) O(H)。取决于树的高度,也就是递归栈的深度。

python 复制代码
# 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:
    pre = -inf
    # def isValidBST(self, root: Optional[TreeNode]) -> bool:

    # 传入初始值,就能用原函数递归
    def isValidBST(self, root: Optional[TreeNode], low=-float('inf'), high=float('inf')) -> bool:

        if not root:
            return True
    
        
        # 递归时,动态更新左右子树的禁区
        return low < root.val < high and self.isValidBST(root.left, low, root.val) and self.isValidBST(root.right, root.val, high)
相关推荐
Navigator_Z15 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木18 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.20 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用1 天前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi0111 天前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1112 天前
算法 --模拟
c++·算法·leetcode
Nil2082 天前
leetcode 739每日温度
算法·leetcode·职场和发展